1. 程式人生 > >Ganymed SSH-2 for Java系列2之連線遠端伺服器

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埠改為什麼,我們底層的這個連線方法都不在需要改動了。