JSCH sudo su命令出现“tty”错误。

11

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个回答

14

它对我有用

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接