如何通过JSch Java API执行Linux命令“ dzdo su-john”并在该用户上执行一些命令,例如“ ls -ltr”

时间:2018-10-04 10:16:26

标签: java linux shell unix jsch

我想使用java jsch库连接到远程linux服务器,并使用dzdo su-john命令切换到另一个用户,我想对该用户执行一些命令。我已经尝试了几种方法来满足此要求,但是我无法做到这一点,对此可以提供任何帮助。

 public static void main(String args[])
    {
    String host="xxxxx.yyyy.com";
    String user="user";
    String password="password";
    String command1="dzdo su - lucy";
    try{    
        java.util.Properties config = new java.util.Properties(); 
        config.put("StrictHostKeyChecking", "no");
        JSch jsch = new JSch();
        Session session=jsch.getSession(user, host, 22);
        session.setPassword(password);
        session.setConfig(config);
        session.connect();
        System.out.println("Connected");

        Channel channel=session.openChannel("shell");
        OutputStream ops = channel.getOutputStream();
        PrintStream ps = new PrintStream(ops, true);

         channel.connect();
         ps.println(command1);
         ps.println("ls -ltr");
        InputStream in=channel.getInputStream();
        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();
        System.out.println("DONE");
    }catch(Exception e){
        e.printStackTrace();
    }
}

    }

通过执行此代码,我得到这样的输出,并且程序没有停止

 Connected
Last login: Thu Oct  4 13:24:38 2018 from xx.xx.xxx.xx

    $  dzdo su - lucy
    xxxx@zr1.xxxx.com:/u/zr1.xxxx.com/lucy $ 

命令ls -ltr没有执行。该程序将在语句while(true){--- code ---}

中进入无限循环

1 个答案:

答案 0 :(得分:2)

可能是时间安排问题。

考虑在两个Thread.sleep调用之间添加println

ps.println(command1);
Thread.sleep(1000);
ps.println("ls -ltr");

或尝试禁用PTY:

((ChannelShell)channel).setPty(false);
channel.connect();

如果可以,那么它比延迟更可靠。

相关问题