Ganymed SSH-2 for Java库是一个用于在Java应用程序中进行SSH连接的库。当使用GanymedConnection连接到Linux机器时,如果机器关机了,连接操作会立即失败并抛出异常。

GanymedConnection不会等待机器重新启动或默认超时时间。如果需要等待机器重新启动并返回结果,你可以使用Java的线程睡眠功能,在适当的时间后再尝试连接。

以下是一个示例代码,演示如何使用GanymedConnection并等待一段时间后再次尝试连接:

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.GanymedSSHException;
import ch.ethz.ssh2.Session;

public class SSHExample {
    private static final String HOST = "your_linux_host";
    private static final String USERNAME = "your_username";
    private static final String PASSWORD = "your_password";

    public static void main(String[] args) {
        Connection conn = new Connection(HOST);
        try {
            conn.connect();
            boolean isAuthenticated = conn.authenticateWithPassword(USERNAME, PASSWORD);
            if (isAuthenticated) {
                Session session = conn.openSession();
                session.execCommand("your_command");
                // Wait for some time before checking if the machine is back online
                Thread.sleep(60000); // Wait for 1 minute
                // Try reconnecting
                conn = new Connection(HOST);
                conn.connect();
                isAuthenticated = conn.authenticateWithPassword(USERNAME, PASSWORD);
                if (isAuthenticated) {
                    session = conn.openSession();
                    session.execCommand("your_command");
                    // Handle the result
                }
            }
        } catch (GanymedSSHException e) {
            // Handle the exception
        } catch (InterruptedException e) {
            // Handle the exception
        }
    }
}

在上述示例代码中,我们首先连接到Linux机器并进行身份验证。然后,我们执行命令,然后线程睡眠1分钟。然后,我们再次尝试连接并进行身份验证,然后再次执行命令。你可以根据需要调整等待时间。

请注意,这种方法需要你自己处理异常和结果处理。你可以根据自己的需求进行修改和定制

java使用GanymedConnection使用ssh连接linux如果机器关机了默认多长时间返回结果

原文地址: http://www.cveoy.top/t/topic/hLF5 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录