ch.ethz.ganymed包ganymedssh2的使用

      最近做测试的自动化实现,需要实现在windows环境下通过跳板机登陆到测试机,运行测试机上某个shell脚本的功能,看了以前的一些参考代码,采用的是Runtime.exec("\"C:\\Program Files\\SecureCRT\\vsh.exe \" -pw 密码 ***@***  sh  **.sh")这样的方式来实现的,后来试用了一下,发现通过跳板机到达测试机能实现,但是中间有点辗转,而且,登陆到测试机上以后执行shell脚本结果时好时坏,由于不太熟悉,个人觉得应该是流没有控制好,或者是线程之类的原因。于是寻找到另外一种方法来实现相同的功能,引入ganymed-ssh2-build210.jar。

    Ganymed SSH-2 for Java是用纯Java实现SSH-2协议的一个包。在使用它的过程中非常容易,只需要指定合法的用户名口令,或者授权认证文件,就可以创建到远程 Linux主机的连接,在建立起来的会话中调用该Linux主机上的脚本文件,执行相关操作。
使用方法:
    在pom.xml中加入配置:

<dependency>
<groupId>ch.ethz.ganymed</groupId>
<artifactId>ganymed-ssh2</artifactId>
<version>build210</version>
</dependency>

     使用实例:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

public class GanymedTest {

	public static void main(String[] args) {

		try {

			Connection conn = new Connection("测试机IP");
			conn.connect();
			boolean isAuthenticated = conn.authenticateWithPassword("username",
					"password");
			if (isAuthenticated == false)
				throw new IOException("Authentication failed.");
			Session sess = conn.openSession();
			sess.execCommand("ls \n  ");
			InputStream stdout = new StreamGobbler(sess.getStdout());
			BufferedReader br = new BufferedReader(
					new InputStreamReader(stdout));
			while (true) {
				String line = br.readLine();
				if (line == null)
					break;
				System.out.println(line);
			}
			sess.close();
			conn.close();
		} catch (IOException e) {
			e.printStackTrace(System.err);

			System.exit(2);
		}

	}
}


 

      这样即可直接通过用户名和密码直接登陆到测试机上,进行相关操作,不会出现线程、阻塞等引起的执行结果时好时坏的情况。

转自:http://testing.etao.com/node/421

原文地址:https://www.cnblogs.com/blogyuan/p/2849954.html