SSH客户端使用—Ganymed SSH-2 for Java

方鸿振
2023-12-01
package com.test;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.junit.Test;

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

import com.util.ConnectionUtils;

/**
 * Ganymed SSH-2 for Java
 * @author bain
 * http://www.ganymed.ethz.ch/ssh2/
 *
 */
public class SSH2TestDemo {

	@Test
	public void test1() throws Exception {
		Connection conn = ConnectionUtils.getConnection("192.168.94.128");
		conn.connect();

		boolean isAuthenticated = conn.authenticateWithPassword("bain", "521");

		if (isAuthenticated) {
			System.out.println("授权成功");
		}

		Session session = conn.openSession();
		// 执行命令
		// session.execCommand("ls -al ");
		// 查看文章内容,将文章内容返回到客户端
		session.execCommand("ls  -al");
		// 阻塞访问数据流
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				session.getStdout()));

		String line = null;
		while ((line = reader.readLine()) != null) {
			System.out.println(line);
		}
		// 如果执行结果正确的话,返回结果为0,
		// 执行结果出错的话,返回127.
		System.out.println("反映结果为" + session.getExitStatus());
		Integer result = session.getExitStatus();
		// 出现错误--只有在执行结果出现错误时,session.getStderr()才会返回inputstream
		BufferedReader reader2 = new BufferedReader(new InputStreamReader(
				session.getStderr()));
		String line1 = null;
		while ((line1 = reader2.readLine()) != null) {//如果执行结果正确的话,就不会执行此while循环 
			System.out.println(line1);
		}
		
		
		//一个session只能用于执行一个命令,如果想要同时执行多个命令的话,那么可以通过创建多个connection完成
		//如果一个命令执行完毕之后,需要将创建的session关闭
		session.close();
		
		session=conn.openSession();
		session.execCommand(" cd /");
		session.close();
		conn.close();
	}
}

 

 类似资料: