Java 如何判断连接何时“完成”?
我不知道这是合理的还是别人想要的,但是 使用和,我没有成功地理解这一切 当您连接到以创建shell并发送命令并等待其完成时,是否有方法检测或获得作业已完成的通知 可以接受三种解决方案: 1获取通知信号、事件等 2读取布尔标志、退出状态、其他 3实时读取输出并解析完成语句 以下是我一直使用的:Java 如何判断连接何时“完成”?,java,ssh,Java,Ssh,我不知道这是合理的还是别人想要的,但是 使用和,我没有成功地理解这一切 当您连接到以创建shell并发送命令并等待其完成时,是否有方法检测或获得作业已完成的通知 可以接受三种解决方案: 1获取通知信号、事件等 2读取布尔标志、退出状态、其他 3实时读取输出并解析完成语句 以下是我一直使用的: import java.io.ByteArrayInputStream; import java.io.InputStream; import com.jcraft.jsch.Ch
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();
}
}
我建议采纳TODO评论中的建议,不要将所有内容都转储到System.out。相反,您希望以InputStream的形式获取从远程主机发送的数据。通过读取流,您应该能够确定何时连接、作业何时完成处理以及连接何时关闭。因此,这就是我不知道如何做的。我找到了这个。那么,channel.getInputStream?是的,channel.getInputStream是您想要的。下面是一个使用它从远程主机检索文件的好例子: