JSCH sudo su命令“tty”错误

时间:2013-01-08 17:19:08

标签: sudo jsch tty su

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;
    }

在sudo.java中的jsch可用示例,他们建议使用

// 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"这样的命令时仍然会给我同样的错误

任何帮助表示感谢。

1 个答案:

答案 0 :(得分:11)

它对我有用

String command = "sudo su - bumboo";
channel.setPty(true);
相关问题