【问题标题】:How to execute linux command "dzdo su - john" through JSch java api and execute some commands like "ls -ltr" on that user如何通过JSch java api执行linux命令“dzdo su - john”并对该用户执行一些命令,如“ls -ltr”
【发布时间】:2019-03-09 16:45:35
【问题描述】:

我想使用 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---}

【问题讨论】:

    标签: java linux shell unix jsch


    【解决方案1】:

    这可能是时间问题。

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

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

    或者尝试禁用 PTY:

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

    如果可行,它是比延迟更可靠的解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-31
      • 2011-08-15
      • 1970-01-01
      • 1970-01-01
      • 2018-11-21
      相关资源
      最近更新 更多