通过JSch运行Pbrun命令后无法执行多个命令

时间:2018-04-13 07:44:36

标签: java unix ssh jsch channel

执行Pbrun后,我无法继续执行第二个命令。请在下面找到我的代码:

public class SSHUploader {

    Session session = null;
    String host="***.**.**.***";
    String user="******";
    String password="*******";
    String script ="pbrun myser -u someuser; cd /tmp; sh tmp.sh status";

    public SSHUploader(){

    }

    public void connect(){
        String pbrunAccess="pbrun myser -u someuser";
        String moveToScriptFolder ="cd /tmp; sh tmp.sh status";
    try {

            JSch jsch = new JSch();
            session = jsch.getSession(user, host, 22);
            session.setPassword(password);
            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            session.connect();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }


    public void executeCommand(String script) throws JSchException, IOException{
        System.out.println("Execute sudo");
        String sudo_pass = "test";
        ChannelExec channel = (ChannelExec) session.openChannel("exec");
        ((ChannelExec) channel).setCommand( script);

        InputStream in = channel.getInputStream();
        OutputStream out = channel.getOutputStream();
        ((ChannelExec) 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) {
                System.out.println(ee);
            }
        }
        channel.disconnect();
        System.out.println("Sudo disconnect");
    }

    public void disconnect(){
        session.disconnect();
    }


    public static void main(String... args) throws JSchException, IOException {

        SSHUploader up = new SSHUploader();
        up.connect();

        up.executeCommand("pbrun myser -u someuser; cd /tmp; sh tmp.sh status");

        up.disconnect();
    }

}

输出:

  

执行sudo使用-u选项成功登录。如果你想允许X.   流量请使用-x选项。

     

su from myuser to someuser at Fri Apr 13 08:35:48 BST 2018

请告诉我缺少的地方。 非常感谢。

0 个答案:

没有答案