[英]Jsch exit status always -1
在這里遇到問題,希望有人可以幫助您:
public void doSomeStuff(){
JSch sConn = new JSch();
try {
sConn.addIdentity("/path/to/privatekey","/path/to/public/key",null);
} catch (JSchException e) {
e.printStackTrace();
}
Session session = null;
try {
session = sConn.getSession("userid", "localhost", 22);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
} catch (JSchException e) {
e.printStackTrace();
}
ChannelExec channel = null;
try {
channel = (ChannelExec) session.openChannel("exec");
BufferedReader in=new BufferedReader(new InputStreamReader(channel.getInputStream()));
channel.setCommand("ls -la;");
channel.connect();
String msg=null;
while((msg=in.readLine())!=null){
System.out.println(msg);
}
} catch (JSchException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(channel.getExitStatus());
channel.disconnect();
System.out.println(channel.isClosed());
System.out.println(channel.getExitStatus());
session.disconnect();
System.out.println(channel.getExitStatus());}
盡管ls -la返回期望的輸出,但在這種情況下,channel.getExitStatus()始終返回-1。 在http://epaul.github.io/jsch-documentation/simple.javadoc/com/jcraft/jsch/Channel.html#getExitStatus%28%29上閱讀該文檔后,我得知該通道必須關閉,因此可以返回退出狀態,否則返回-1,但就我而言,我始終為-1。
任何人都知道在這種情況下是什么問題?
使用JCraft的示例中的代碼,我重新構建了對輸入流的處理,並使其與以下代碼一起工作:
public void doSomeStuff(){
JSch sConn = new JSch();
try {
sConn.addIdentity("/home/user/.ssh/id_rsa","/home/user/.ssh/id_rsa.pub",null);
} catch (JSchException e) {
e.printStackTrace();
}
Session session = null;
try {
session = sConn.getSession("user", "localhost", 22);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
} catch (JSchException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ChannelExec channel = null;
try {
channel = (ChannelExec) session.openChannel("exec");
channel.setCommand("lsa;");
((ChannelExec)channel).setCommand("ls -la");
InputStream in = channel.getInputStream();
((ChannelExec)channel).setErrStream(System.err);
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();
session.disconnect();
}
catch(Exception e){
System.out.println(e);
}
channel.disconnect();
session.disconnect();
System.out.println(channel.getExitStatus());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.