Library JSch,Sudo脚本不适用于Centos

时间:2017-04-20 12:54:21

标签: java linux ssh sudo jsch

我正在使用JSсh库。我需要关闭计算机Linux操作系统(Ubuntu,Fedor®,Centos)。 Ubuntu和Fedoro没有问题。但有Centos问题。 我只能在用户“root”下关闭。但是如果我将用户“john”与超级用户的权限一起使用,则脚本会在输入密码时挂起,并且没有任何反应。我将非常感谢任何帮助。 下面我提供代码

public class Sudo {
private static final int timeout = 10000;
public static String sudo_pass = "john123";

public static void main(String[] arg) {
        try {
            JSch jsch = new JSch();
            String user = "john";
            String host = "192.168.56.103";
            Session session = jsch.getSession(user, host, 22);
            UserInfo ui = new MyUserInfo();
            session.setUserInfo(ui);
            session.connect(timeout);

            String command = "sudo poweroff";

            ChannelExec channel = (ChannelExec) session.openChannel("exec");

            // 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.

            channel.setCommand("sudo -S -p '' " + command);
            channel.setPty(true);

            InputStream in = channel.getInputStream();
            OutputStream out = channel.getOutputStream();

            channel.setErrStream(System.err);

            channel.connect();

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

            byte[] tmp = new byte[1024];
            while (true) {
                while (in.available() > 0) {
                    int i = in.read(tmp, 0, 1024);
                    if (i < 0) break;
                    System.out.print(new String(tmp, 0, i));
                }
                if (channel.isClosed()) {
                    System.out.println("exit-status: " + channel.getExitStatus());
                    break;
                }
                try {
                    Thread.sleep(1000);
                } catch (Exception ee) {
                }
            }
            channel.disconnect();
            session.disconnect();
        } catch (Exception e) {
            System.out.println(e);
        }

    }
}

enter image description here

0 个答案:

没有答案