有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java check server是否在网络中可用,请使用JSCH

我用JSCH lib在远程机器上执行一些mongodb命令,我有一个程序,它有三种方法

  • connect(serverIP, userName, password):它将连接到服务器,并且没有线路

    session.connect()抛出以下异常

If invalid credentails: JschException:Auth Fail

If SSH is not enabled in server :JschException:java.net.ConnectException: Connection refused



If server is not in network: JschException:java.net.NoRouteToHostException: No route to host
  • executeCommand(command):它将执行命令并打印结果
  • disconnect():它将与服务器断开连接

我在下面附上了三种方法的代码

问题:如果我们在不知道服务器是否在网络中可用的情况下使用session.connect(),则其抛出异常JschException:NotRouteToHostException

是否有任何方法来验证服务器是否在网络中可用,而不是获取异常

如果是,我们如何验证

 public void connect(String serverIP, String serverUserName, String password ){
            JSch jsch = new JSch();
            try {
                session = jsch.getSession(serverUserName, serverIP, 22);
            } catch (JSchException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            session.setPassword(password);
            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            try {
                session.connect();
                
            } catch (JSchException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        
    }
public StringBuffer executeCommand(String script) throws JSchException, IOException{
    String sudo_pass = "test";
    ChannelExec channel = (ChannelExec) session.openChannel("exec");
    ((ChannelExec) channel).setCommand( script);

    InputStream in = channel.getInputStream();
    OutputStream out = channel.getOutputStream();
    ((ChannelExec) channel).setErrStream(System.err);

    channel.connect();
    out.write((sudo_pass + "\n").getBytes());
    out.flush();

    StringBuffer commandResult = new StringBuffer();
    byte[] tmp = new byte[1024];
    while (true) {
        while (in.available() > 0) {
            int i = in.read(tmp, 0, 1024);
            if (i < 0)
                break;
            commandResult.append(new String(tmp, 0, i));
            Logger.of(LoggerConstants.AUTOMATTER_LOGGER).debug(new String(tmp, 0, i));
            Logger.of(LoggerConstants.AUTOMATTER_LOGGER).info(new String(tmp, 0, i));
            //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) {
            System.out.println(ee);
        }
    }
    channel.disconnect();
    System.out.println("Sudo disconnect");
    return commandResult;
}

public void disconnect(){
    session.disconnect();
}

共 (0) 个答案