Ganymed SSH-2 for Java系列2之连接远程服务器

连接远程服务器,新建一个java工具类,将其命名为CommandRunner;

创建一个连接服务器的静态方法:

public static Connection getOpenedConnection(String host, String username,

	String password) throws IOException {

		if (logger.isInfoEnabled()) { 

			logger.info("connecting to " + host + " with user " + username

			+ " and pwd " + password);

		}

		Connection conn = new Connection(host);

		conn.connect(); // make sure the connection is opened

		boolean isAuthenticated = conn.authenticateWithPassword(username,

		password);

		if (isAuthenticated == false)

			throw new IOException("Authentication failed.");

		return conn;

	}

测试代码:

public static void main(String[] args) {
		Connection conn = null;
		try {
			conn = CommandRunner.getOpenedConnection("172.16.18.141", "root",
					"123456");

			if (null != conn) {
				System.out.println("连接服务器成功!");
			}

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			conn.close();
			conn = null;
		}

	}

执行结果:


log4j:WARN No appenders could be found for logger (com.ssh2.shell.ganymed.CommandRunner).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
连接服务器成功!


至此,连接服务器的静态方法完成,但是这样处理会存在一个问题,就是我们都知道ssh默认端口是22,如果服务器的ssh 端口不是22,那么这个连接服务器的代码是不是就不可以用了啦,所以需要简单的修改下 ,修改如下:

方法增加一个端口参数:


	public static Connection getOpenedConnection(String host, String username,

	String password,int port) throws IOException {

连接的地方将参数放进去:

	Connection conn = new Connection(host,port);

这样不论ssh端口改为什么,我们底层的这个连接方法都不在需要改动了。




你可能感兴趣的:(Ganymed SSH-2 for Java系列2之连接远程服务器)