我想通过我的java程序在ssh上执行多个命令。基于执行结果,我需要在同一个shell上执行一些更多的命令。但是当我试图执行它正在采取不同的外壳。如果有人知道这个决议是非常赞赏的。如何使用相同的shell通过JSCH执行多个unix命令?
这里是我的代码片段
public class sshconnectionTest {
JSch jsch = new JSch();
Session session;
Channel channel;
public Session openSession() throws Exception {
if (null == session) {
session = jsch.getSession("user", "hostname",
22);
System.out.println("**************************************"
+ session.isConnected());
AESencrp aesEncrypt = new AESencrp();
session.setPassword("pwd");
session.setConfig("StrictHostKeyChecking", "no");
session.connect(10 * 1000);
}
return session;
}
public Channel openChannel(Session session) throws Exception {
if (null == channel) {
channel = session.openChannel("exec");
}
return channel;
}
public String getSession(String command1) throws Exception {
try {
session = openSession();
channel = openChannel(session);
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];
String readText = "";
while (true) {
while (in.available() > 0) {
int i = in.read(tmp, 0, 1024);
if (i < 0)
break;
readText = new String(tmp, 0, i);
System.out.print(readText);
}
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 (Throwable t) {
System.out.println(t);
}
return null;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
sshconnectionTest sshcon = new sshconnectionTest();
String command1 = " env | grep CCM;";
String session = sshcon.getSession(command1);
String command = "export SRL_FILE=/home/20140224/myfile.txt;";
sshcon.getSession(command);
sshcon.getSession("env | grep SRL;");
sshcon.getSession("pwd");
} catch (Exception e) {
}
}
}
`
我做了相同的更改,但仍然需要不同的shell。它不会保留相同的外壳。 – Sachin
如果您使用相同的连接,会话和通道,那么它将会是相同的shell。你做错了什么......:/ ...仔细看看我是怎么做到的。我设置了私有字段一次,然后离开它们(包括jsch,channel和session对象,这意味着,每次使用同一个对象时,它都是一样的。 – SnakeDoc