Ganymed SSH-2 for Java系列3之执行远程shell 命令

16 篇文章 0 订阅
14 篇文章 0 订阅

利用Ganymed SSH-2 for Java 连接到远程服务器,然后执行shell命令;


首先我们再在之前CommandRunner类中再添加一个执行shell命令的方法,具体如下所示:


public static String execShellScript(String host, String username,
			String password,

			String cmd, int port) throws IOException {

		if (logger.isInfoEnabled()) {

			logger.info("running SSH cmd [" + cmd + "]");

		}

		Connection conn = null;

		Session sess = null;

		InputStream stdout = null;

		BufferedReader br = null;

		StringBuffer buffer = new StringBuffer("exec result:");
		buffer.append(System.getProperty("line.separator"));// 换行
		try {

			conn = getOpenedConnection(host, username, password, port);

			sess = conn.openSession();

			sess.execCommand(cmd);

			stdout = new StreamGobbler(sess.getStdout());

			br = new BufferedReader(new InputStreamReader(stdout));

			while (true) {

				// attention: do not comment this block, or you will hit
				// NullPointerException

				// when you are trying to read exit status

				String line = br.readLine();

				if (line == null)

					break;
				
				buffer.append(line);
				buffer.append(System.getProperty("line.separator"));// 换行

				if (logger.isInfoEnabled()) {

					logger.info(line);

				}

			}

		} finally {

			sess.close();

			conn.close();

		}

		return buffer.toString();

	}


测试代码:

public static void main(String[] args) {
		
		String cmd = "uname -a";
		
		try {
			String info = CommandRunner.execShellScript("172.16.18.141", "root",
					"123456",cmd,22);
			
			System.out.println("info is:"+info);
		} catch (IOException e) {
			e.printStackTrace();
		}

	}



执行结果

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.
info is:exec result:
Linux localhost.localdomain 2.6.32-220.el6.x86_64 #1 SMP Wed Nov 9 08:03:13 EST 2011 x86_64 x86_64 x86_64 GNU/Linux


至此,连接远程服务器执行shell命令简单方法就实现了。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值