2012-07-20 396 views
2

我正嘗試使用JSch在目標主機上運行命令,並希望能夠指示密碼,例如:「sudo echo hello」和然後輸入當前用戶的密碼。如何使用Jsch通過SSH運行需要密碼的命令

我不明白如何正確地與提示進行交互。下面的代碼顯示兩種方法我試過提供密碼,他們都失敗消息:

須藤:沒有TTY出現,也沒有askpass程序指定

我有這方面的工作:

JSch jsch=new JSch(); 
String host="192.168.0.17"; 
String user="xxx"; 
String passwd="xxx"; 

Session session=jsch.getSession(user, host, 22); 
session.setPassword(passwd); 
session.setConfig("StrictHostKeyChecking", "no"); 
session.connect(); 

ChannelExec channel=(ChannelExec)session.openChannel("exec"); 
channel.setCommand("sudo echo hello"); 
channel.setErrStream(System.err); 
channel.connect(); 


int id = 1; 
// must write on output stream? 
if(id==0){ 
channel.getOutputStream().write(passwd.getBytes()); 
} 
// must read on input stream? 
else if(id==1){ 
channel.getInputStream().read(passwd.getBytes()); 
} 

channel.disconnect(); 

感謝您的建議!

回答

相關問題