我想在远程系统上执行命令,并希望获得相同的结果。
我尝试了以下代码:
package rough;
import java.io.InputStream;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class RemoteSSH {
public static void main(String[] args) {
String host = "\\\\10.209.110.114";
String user = "Administrator";
String password = "Admin123";
String command1 = "ipconfig";
try {
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, 22);
session.setPassword(password);
session.setConfig(config);
session.connect();
System.out.println("Connected");
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command1);
channel.setInputStream(null);
((ChannelExec) channel).setErrStream(System.err);
InputStream in = channel.getInputStream();
channel.connect();
byte[] tmp = new byte[1024];
while (true) {
while (in.available() > 0) {
int i = in.read(tmp, 0, 1024);
if (i < 0)
break;
System.out.print(new String(tmp, 0, i));
}
if (channel.isClosed()) {
System.out.println("exit-status: " + channel.getExitStatus());
break;
}
try {
Thread.sleep(1000);
} catch (Exception ee) {
}
}
channel.disconnect();
session.disconnect();
System.out.println("DONE");
} catch (Exception e) {
e.printStackTrace();
}
}
}
但是我收到了以下错误:
com.jcraft.jsch.JSchException: java.lang.IllegalArgumentException: protocol = socket host = null
at com.jcraft.jsch.Util.createSocket(Util.java:258)
at com.jcraft.jsch.Session.connect(Session.java:186)
at com.jcraft.jsch.Session.connect(Session.java:145)
at rough.RemoteSSH.main(RemoteSSH.java:23)
Caused by: java.lang.IllegalArgumentException: protocol = socket host = null
at sun.net.spi.DefaultProxySelector.select(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at com.jcraft.jsch.Util.createSocket(Util.java:252)
... 3 more
任何解决方案。 我已经尝试过使用pstool,但没有得到正确的输出。
答案 0 :(得分:5)
我的猜测是你没有在目标机器上运行SSH服务器。
请注意,Windows没有任何内置SSH服务器。
确保先安装一些SSH服务器 见Is IIS SFTP natively supported by Windows Server 2012 R2?
或使用其他技术运行命令:
Best way to run remote commands on a Windows server from Java?