为什么通过shell通道运行多个命令时不能连续一致地运行? (JSch)

时间:2019-01-28 17:55:36

标签: java ssh jsch

我正在使用Jsch在远程服务器上运行Shell脚本,并设法在该服务器上进行升级(感谢您回答问题here),但是我的代码仍然存在一些问题。

  1. 它不会依次运行命令,并且不会始终使用printscreen.println()方法给出命令。
  2. 我的程序在带有某些断点的调试模式下可以很好地执行shell命令,但是在运行模式或没有调试点的情况下无法执行命令。
ps.println()方法的runScript方法中的

命令不能按顺序运行。在运行模式下,printResilt()方法也无法打印(执行)命令。

    public void runScript(Channel channel) throws Exception {
    // Gets an InputStream for this channel. All data arriving in as messages from the remote side can be read from this stream.
    try {

        OutputStream ops = channel.getOutputStream();
        PrintStream ps = new PrintStream(ops, true);

        channel.setOutputStream(System.out, true);

        // Execute the command
        channel.connect();

        InputStream in = channel.getInputStream();

        ps.println("sudo su - sudouser");
        ps.println("ksh -x \"/path/to/script/shellscript.sh\" arg1  arg2 arg3 arg4 arg5 arg6  arg7");
        ps.println("exit");
        ps.close();

        printResult(in, channel);
    }
    catch(IOException ioExp) {
        ioExp.printStackTrace();
    }


//retrieve the exit status of the remote command corresponding to this channel
 //int exitStatus = channelExec.getExitStatus();

    //Safely disconnect channel and disconnect session. If not done then it may cause resource leak
    channel.disconnect();
    session.disconnect();
}
 /**
    * @param input
    * @param channel
    */
   private static void printResult(InputStream in,
                                   Channel channel) throws Exception
   {
      int SIZE = 1024;
      byte[] tmp = new byte[SIZE];
      while (true) {
          try {
              Thread.sleep(1000);
          } catch (Exception ee) {}
          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()) {
               if(in.available() > 0) {
                  int i = in.read(tmp, 0, 1024);
                  System.out.print(new String(tmp, 0, i));
               } 
              System.out.println("exit-status: " + channel.getExitStatus());
              break;
          }

      }
   }

主要方法:

public class App 
{

public static void main( String[] args ) throws Exception
{   
    try
    {
        SFTPUploader sftpUploader = new SFTPUploader();
        ChannelSftp sftpChannel = sftpUploader.connectServer();

        //close sftp channel after upload
        sftpUploader.closeChannel(sftpChannel);

        //open executable channel
        Channel channel = sftpUploader.openChannel("shell");

        //execute shell script
        sftpUploader.runScript(channel);
    }
    catch(SftpException e) {
        e.printStackTrace();
    }
    catch(JSchException jschExp) {
        jschExp.printStackTrace();
    }
 }
}

0 个答案:

没有答案