I managed to execute a single command through ssh with Jsch but when i try to execute a second command it fails
For debugging i brought this problem down to this lines:
import java.io.IOException;
import java.io.InputStream;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
public class Exec {
public static void test(Session session) throws Exception {
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand("pwd");
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();
}
public static void main(String[] arg) {
try {
JSch jsch = new JSch();
Session session = jsch.getSession("nck", "127.0.0.1", 22);
session.setPassword("asd");
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
test(session); // This one succeeds with exit-status: 0
test(session); // This one fails with exit-status: 255
session.disconnect();
} catch (Exception e) {
//
}
}
}
This is mostly the official Exec example but this gives me this output:
/home/nck
exit-status: 0
exit-status: 255
The first command is executed succesfully the second doesnt.
Any Ideas ?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…