我正在尝试使用API JSch编写用于将SSH连接到Switch Alcatel-Lucent 7210 SAS-X并发送一些命令和接收输出的脚本。但不幸的是,它不适用于连接类型«exec» - 退出状态-1 当我使用连接类型«shell»与输入/输出思想控制台一切正常。 有人能帮助我吗? 下面是我的脚本。
import com.jcraft.jsch.*;
import java.io.IOException;
import java.io.InputStream;
import java.util.Hashtable;
public class SSHTunel2 {
public static void main(String[] args) {
String IPaddress_server="X.X.X.X";
String User_server="admin";
int Port_server=22;
String Password_server="1111111";
String Switch_command ="show version";
try {
JSch jsch = new JSch();
// Connection to the Server
Session session1=jsch.getSession(User_server, IPaddress_server);
session1.setPassword(Password_server);
Hashtable<String, String> config = new Hashtable<String, String>();
config.put("StrictHostKeyChecking", "no");
session1.setConfig(config);
session1.connect();
System.out.println("session1.getServerVersion():"
+session1.getServerVersion();
System.out.println("The session has been established to
+User_server+"@"+IPaddress_server);
//Command execution
Channel channel=session1.openChannel("exec");
((ChannelExec)channel).setCommand(Switch_command);
channel.setInputStream(null);
InputStream in=channel.getInputStream();
channel.connect();
// Channel channel=session1.openChannel("shell");
// channel.setInputStream(System.in);
// channel.setOutputStream(System.out);
// 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()){
if(in.available()>0) continue;
System.out.println("exit-status:
"+channel.getExitStatus());
break;
}
try{Thread.sleep(1000);}catch(Exception ee){}
}
channel.disconnect();
session1.disconnect();
} catch (JSchException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
/* Output */
session1.getServerVersion(): SSH-2.0-OpenSSH_3.5p1
The session has been established to admin@10.44.93.106
in.available(): 0
exit-status: -1
Process finished with exit code 0