2013-01-08 86 views
7

Java - Jsch sudo命令。JSCH sudo su命令「tty」錯誤

我使用Jsch,我的任務是登錄到服務器並運行命令如下

sudo su - bumboo 

使用下面的代碼我是能夠成功連接,但是當我嘗試運行命令時,它給我的錯誤sudo: sorry, you must have a tty to run sudo

以下是我的代碼

public static Channel sudoBamboo(Session session, String sudo_pass) throws Exception { 

     ChannelExec channel = (ChannelExec) session.openChannel("exec"); 
     //SUDO to bamboo user 
     String command = "sudo su - bumboo"; 
     channel.setCommand(command); 

     //InputStream in = channel.getInputStream(); 
     channel.setInputStream(null, true); 

     OutputStream out = channel.getOutputStream(); 
     //channel.setErrStream(System.err); 
     channel.setOutputStream(System.out, true); 
     channel.setExtOutputStream(System.err, true); 
     //Test change 
     //channel.setPty(false); 
     channel.connect(); 

     out.write((sudo_pass + "\n").getBytes()); 
     out.flush(); 

     return channel; 
    } 

jsch在sudo.java提供例如他們建議使用

// man sudo 
     // -S The -S (stdin) option causes sudo to read the password from the 
     //  standard input instead of the terminal device. 
     // -p The -p (prompt) option allows you to override the default 
     //  password prompt and use a custom one. 
     ((ChannelExec)channel).setCommand("sudo -S -p '' "+command); 

但是當我運行命令像"sudo -S -p - su bamboo"仍然給我相同的錯誤

任何幫助表示讚賞。

回答

10

它爲我

String command = "sudo su - bumboo"; 
channel.setPty(true);