Java - Jsch sudo命令。
我正在使用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"
仍然给我相同的错误
感谢您的帮助。
我成功了
String command = "sudo su - bumboo";
channel.setPty(true);