【发布时间】:2014-03-07 15:42:58
【问题描述】:
我想通过我的 java 程序在 ssh 上执行多个命令。根据执行结果,我需要在同一个 shell 上执行更多命令。但是当我试图执行它时,它正在使用不同的外壳。如果有人知道该决议非常感谢。
这是我的代码 sn-p
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) {
}
}
}
`
【问题讨论】: