通过JSch远程执行ConnectException

时间:2016-10-24 12:53:03

标签: java jsch

我的目标是使用JCraft的JSch库远程运行命令。代码段如下。我得到了java.net.ConnectException。我不可或缺的目的是从我的系统远程运行批处理文件。

代码段:

String command = "ipconfig"; //Or any execution command
String host = "10.10.*.*";
String user = "username";
String password = "password";

JSch jsch = new JSch();
Session session = jsch.getSession(user, host, 22);

Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);;
session.setPassword(password);
session.connect();
session.setHost(host);

UserInfo userInfo = new MyUserInfo();
session.setUserInfo(userInfo); 
Channel channel = session.openChannel("exec");

((ChannelExec)channel).setCommand(command);
channel.setInputStream(null);
((ChannelExec)channel).setErrStream(System.err);

InputStream input = channel.getInputStream();
channel.connect();

System.out.println("Channel Connected to machine " + host + " server with command: " + command ); 


try{
    InputStreamReader inputReader = new InputStreamReader(input);
    BufferedReader bufferedReader = new BufferedReader(inputReader);
    String line = null;

    while((line = bufferedReader.readLine()) != null){
        System.out.println(line);
    }
    bufferedReader.close();
    inputReader.close();

错误:

com.jcraft.jsch.JSchException: java.net.ConnectException: Connection timed   out: connect
at com.jcraft.jsch.Util.createSocket(Util.java:349)
at com.jcraft.jsch.Session.connect(Session.java:215)
at com.jcraft.jsch.Session.connect(Session.java:183)
at RemoteExecution.execute(RemoteExecution.java:125)
at PutFilesToUnix.main(PutFilesToUnix.java:127)
Caused by: java.net.ConnectException: Connection timed out: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(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:343)
... 4 more

1 个答案:

答案 0 :(得分:0)

我的代码中没有看到连接超时/会话超时属性。尝试添加可能有用的会话超时参数。不确定是否要设置这些参数连接可以等待连接的时间。还尝试下载任何开源客户端,看看您是否可以手动连接。