远程SSH在几次迭代后停止响应

时间:2015-07-09 10:56:15

标签: java ssh network-programming jsch ssh2-exec

编写java程序以建立远程SSH连接,并在JSch的帮助下向该SSH设备发送命令。并且该代码需要运行无限循环意味着代码将与第一个设备建立连接,向其发送命令并移动到第二个设备。完成向第十个设备发送命令后,代码将从第一个设备重新开始。对于两到三次迭代,它工作正常。但是,下一次迭代以后没有从设备获得任何响应,但连接建立成功并且代码被卡在该设备上。请帮忙解决这个问题,设备方面没有问题。如果它也被卡住,代码需要等待一段时间并开始与下一个设备建立连接。

代码是:

public class SSHManager {
    private JSch shell;
    private Session session;
    private Channel channel;
    private static OutputStream out;
    private static InputStream in;

    public void connect(String username, String password, String host,int port)
        throws JSchException, IOException, InterruptedException {
        shell = new JSch();
        session = shell.getSession(username, host, port);
        session.setPassword(password);
        session.setConfig("StrictHostKeyChecking", "no");
        session.connect();

        channel=session.openChannel("shell");
        channel.setInputStream(null);
        channel.setOutputStream(null);

        in=channel.getInputStream();
        out =channel.getOutputStream();
        ((ChannelShell)channel).setPtyType("vt102");
         channel.connect();
    }

    public String send(String command) throws IOException, InterruptedException {
        byte[] tmp=new byte[1024];

        out.write((command+";echo \"z4a3ce4f3317Z\"").getBytes());
        out.write(("\n").getBytes());
        out.flush();

        String result = "";
        while(true){
            while(in.available()>0){
                int i=in.read(tmp, 0, 1024);
                if(i<0)
                    break;

                result = result + (new String(tmp, 0, i));
            }

            if(result.indexOf("z4a3ce4f3317Z") != -1){
                break;
            }

            try{Thread.sleep(300);}catch(Exception ee){}
        }

        return result;
    }

    public boolean isConnected() {
        return (channel != null && channel.isConnected());
    }

    public void disconnect() {
        if (isConnected()) {
            channel.disconnect();
            session.disconnect();
        }
    }
}

class Test {

    final static SSHManager client = new SSHManager();
    public static void main(String[] args) throws JSchException, IOException, InterruptedException {
        while(true) {

            try
            {
                for (int i=1;i<=10;i++)
                {
                    String ipaddr = "10.35.57."+i;    
                    System.out.println(ipaddr);
                    client.connect("root", "root", ipaddr, 22);
                    client.send("cd /\n");
                    Thread.sleep(3500);
                    client.send("rm sett*");
                    // Send five more commands to that device
                }
            }
            catch(Exception e)
            {
                System.out.println(e);
            }
            Thread.sleep(150*1000); 
        }
     }
 }

0 个答案:

没有答案