Written java program to establish remote SSH connection and send commands to that SSH device with the help of JSch. And that code need to run infinite loop means code will establish connection with first device, sends commands to that and moves to second device. After completion of sending commands to tenth device code will start again from the first device. For two to three iterations it is working fine. But, next iteration onwards not getting any response from device but connection establishment was successful and code was stuck at that device. Please help to solve this, there is no issue from device side. If it is stuck also, code needs to wait some time and start establish connection with next device.
Code is:
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);
}
}
}