如何判断连接何时“完成”?

时间:2014-03-24 02:04:57

标签: java ssh

我不知道其他人是否合理或期望,但......

使用JSchAPI,我无法理解这一切。

当您使用Session连接以创建shell Channel并发送命令并等待它完成时,有没有办法检测或获得作业已完成的通知?

三种解决方案是可以接受的: 1)获取通知(信号,事件,其他) 2)读取标志(布尔值,退出状态,其他) 3)实时读取输出并解析完成语句

这是我一直在使用的template

    import java.io.ByteArrayInputStream;
    import java.io.InputStream;

    import com.jcraft.jsch.Channel;
    import com.jcraft.jsch.JSch;
    import com.jcraft.jsch.JSchException;
    import com.jcraft.jsch.Session;

    /** Demonstrates a connection to a remote host via SSH. **/
    public class ExecuteSecureShellCommand
    {
      private static final String user = ""; // TODO: Username of ssh account on remote machine
      private static final String host = ""; // TODO: Hostname of the remote machine (eg: inst.eecs.berkeley.edu)
      private static final String password = ""; // TODO: Password associated with your ssh account
      private static final String command = "ls -l\n"; // Remote command you want to invoke

      public static void main(String args[]) throws JSchException, InterruptedException
      {
        JSch jsch = new JSch();

        // TODO: You will probably want to use your client ssl certificate instead of a password
        // jsch.addIdentity(new File(new File(new File(System.getProperty("user.home")), ".ssh"), "id_rsa").getAbsolutePath());

        Session session = jsch.getSession(user, host, 22);

        // TODO: You will probably want to use your client ssl certificate instead of a password
        session.setPassword(password);

        // Not recommended - skips host check
        session.setConfig("StrictHostKeyChecking", "no");

        // session.connect(); - ten second timeout
        session.connect(10*1000);

        Channel channel = session.openChannel("shell");

        // TODO: You will probably want to use your own input stream, instead of just reading a static string.
        InputStream is = new ByteArrayInputStream(command.getBytes());
        channel.setInputStream(is);

        // Set the destination for the data sent back (from the server)
        // TODO: You will probably want to send the response somewhere other than System.out
        channel.setOutputStream(System.out);

        // channel.connect(); - fifteen second timeout
        channel.connect(15 * 1000);

        // Wait three seconds for this demo to complete (ie: output to be streamed to us).
        Thread.sleep(3*1000);

        // Disconnect (close connection, clean up system resources)
        channel.disconnect();
        session.disconnect();
      }
    }

0 个答案:

没有答案