Ganymed SSH2 模拟putty远程交互式执行命令工具

接着上篇http://blog.csdn.net/doctor_who2004/article/details/47322105的介绍:

我们模拟下putty这类交互式的执行远程命令:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

/**
 * 模拟交互式终端
 *
 * @author doctor
 *
 * @time 2015年8月6日
 *
 * @see http://www.programcreek.com/java-api-examples/index.php?api=ch.ethz.ssh2.SCPClient
 *
 */
public final class SSHAgent2 {
	private Logger log = LoggerFactory.getLogger(getClass());
	private Connection connection;
	private Session session;
	private BufferedReader stdout;
	private PrintWriter printWriter;
	private BufferedReader stderr;
	private ExecutorService service = Executors.newFixedThreadPool(3);
	private Scanner scanner = new Scanner(System.in);

	public void initSession(String hostName, String userName, String passwd) throws IOException {
		connection = new Connection(hostName);
		connection.connect();

		boolean authenticateWithPassword = connection.authenticateWithPassword(userName, passwd);
		if (!authenticateWithPassword) {
			throw new RuntimeException("Authentication failed. Please check hostName, userName and passwd");
		}
		session = connection.openSession();
		session.requestDumbPTY();
		session.startShell();
		stdout = new BufferedReader(new InputStreamReader(new StreamGobbler(session.getStdout()), StandardCharsets.UTF_8));
		stderr = new BufferedReader(new InputStreamReader(new StreamGobbler(session.getStderr()), StandardCharsets.UTF_8));
		printWriter = new PrintWriter(session.getStdin());
	}

	public void execCommand() throws IOException {
		service.submit(new Runnable() {

			@Override
			public void run() {
				String line;
				try {
					while ((line = stdout.readLine()) != null) {
						System.out.println(line);
					}
				} catch (IOException e) {
					e.printStackTrace();
				}

			}
		});

		service.submit(new Runnable() {

			@Override
			public void run() {
				while (true) {
					try {
						TimeUnit.SECONDS.sleep(1);
					} catch (InterruptedException e) {

						e.printStackTrace();
					}
					System.out.print("input:");
					String nextLine = scanner.nextLine();
					printWriter.write(nextLine + "\r\n");
					printWriter.flush();
				}

			}
		});

	}

	public void close() {
		IOUtils.closeQuietly(stdout);
		IOUtils.closeQuietly(stderr);
		IOUtils.closeQuietly(printWriter);
		IOUtils.closeQuietly(scanner);
		session.close();
		connection.close();
	}

	/**
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {
		SSHAgent2 sshAgent = new SSHAgent2();
		sshAgent.initSession("127.0.0.1", "doctor", "xxxx");

		sshAgent.execCommand();

		// sshAgent.close();

	}

}

这里读写流我分别在不同线程下操作,防止读写流之间的阻塞,简单模拟交互环境。当然,登陆的是本地系统,没有安装虚拟机等。

执行结果:

Last login: Thu Aug  6 20:18:52 2015 from 127.0.0.1

input:pwd;
[[email protected] ~]$ pwd;
/home/doctor
[[email protected] ~]$
input:ll
[[email protected] ~]$ ll
总用量 2013760
drwxrwxr-x.  3 doctor doctor      4096 7月  27 21:58 android-sdk_r24.3.3-linux
-rw-rw-r--.  1 doctor doctor 309109716 7月  26 17:05 android-sdk_r24.3.3-linux.tgz
drwxrwxr-x.  7 doctor doctor      4096 7月  29 00:04 android-studio
-rw-rw-r--.  1 doctor doctor 258628239 7月  26 17:01 android-studio-ide-141.1980579-linux.zip
drwxrwxr-x.  3 doctor doctor      4096 7月   5 09:48 app
drwxrwxr-x.  7 doctor doctor      4096 8月   4 22:11 Documents
drwxrwxr-x. 21 doctor doctor      4096 8月   2 21:22 git
drwxrwxr-x.  3 doctor doctor      4096 6月  14 12:03 ideaIU-14.1.3
-rw-rw-r--.  1 doctor doctor 308609842 6月  13 13:36 ideaIU-14.1.3.tar.gz
drwxrwxr-x. 11 doctor doctor      4096 7月  26 12:26 jstorm-0.9.6.3
-rw-rw-r--.  1 doctor doctor  11113536 6月   8 21:19 jstorm-0.9.6.3.zip
drwxrwxr-x.  7 doctor doctor      4096 7月  23 21:24 node_modules
-rw-rw-r--.  1 doctor doctor  20063992 7月  11 11:49 node-v0.12.7.tar.gz
drwxrwxrwx. 18 doctor doctor      4096 8月   2 18:10 opt
-rw-rw-r--.  1 doctor doctor    466053 7月  28 20:05 pljava-x86_64-unknown-linux-gnu-pg9.1-1.4.3.tar.gz
-rwxrwxrwx.  1 doctor doctor    155693 7月  24 21:58 plv8-1.4.4.tar.gz
drwxrwxr-x.  3 doctor doctor      4096 7月  27 23:33 pycharm-professional-4.5.3
-rwxrwxrwx.  1 doctor doctor 160688951 7月  27 22:38 pycharm-professional-4.5.3.tar.gz
drwxrwxr-x.  3 doctor doctor      4096 7月  27 23:35 PycharmProjects
drwxrwxr-x.  3 doctor doctor      4096 6月   9 19:08 spring-tool-suite-3.6.4.RELEASE-e4.4.2-linux-gtk-x86_64
-rwxrwxrwx.  1 doctor doctor 417016357 6月   8 22:13 spring-tool-suite-3.6.4.RELEASE-e4.4.2-linux-gtk-x86_64.tar.gz
drwxrwxr-x.  3 doctor doctor      4096 7月   3 21:14 spring-tool-suite-3.7.0.RELEASE-e4.5-linux-gtk-x86_641
-rwxrwxrwx.  1 doctor doctor 429456394 7月   3 13:20 spring-tool-suite-3.7.0.RELEASE-e4.5-linux-gtk-x86_641.tar.gz
drwxrwxr-x.  8 doctor doctor      4096 7月  23 22:08 tmp
drwxrwxr-x. 10 doctor doctor      4096 11月 12 2014 v8-3.31.1
-rw-rw-r--.  1 doctor doctor  16423158 7月  25 00:28 v8-3.31.1.tar.gz
drwxrwxr-x.  3 doctor doctor      4096 6月   8 20:49 WebStorm-10.0.3
-rw-rw-r--.  1 doctor doctor 130207806 6月   8 20:04 WebStorm-10.0.3.tar.gz
drwxrwxr-x.  5 doctor doctor      4096 7月  29 19:51 WebstormProjects
drwxrwxr-x.  5 doctor doctor      4096 9月  25 2014 zookeeper
drwxrwxr-x.  3 doctor doctor      4096 8月  13 2014 壁纸
drwxr-xr-x.  2 doctor doctor      4096 7月  26 17:00 图片
drwxr-xr-x.  2 doctor doctor      4096 7月  30 23:34 文档
drwxr-xr-x.  2 doctor doctor      4096 8月   5 21:47 下载
drwxr-xr-x.  2 doctor doctor      4096 6月   7 21:44 桌面
[[email protected] ~]$
input:who
[[email protected] ~]$ who
doctor   pts/1        2015-08-06 20:28 (127.0.0.1)
[[email protected] ~]$
input:who am i
[[email protected] ~]$ who am i
doctor   pts/1        2015-08-06 20:28 (127.0.0.1)
[[email protected] ~]$
input:date
[[email protected] ~]$ date
2015年 08月 06日 星期四 20:29:18 CST
[[email protected] ~]$
input:

版权声明:本文为博主原创文章,未经博主允许不得转载[http://blog.csdn.net/doctor_who2004]。

时间: 2024-12-12 11:36:18

Ganymed SSH2 模拟putty远程交互式执行命令工具的相关文章

Ganymed SSH2 模拟类似FileZilla远程传输文件(基于SCP协议)

Ganymed SSH2 模拟类似FileZilla远程传输文件(基于SCP协议) 为了传输文件或者目录,我们使用 Ganymed SSH2中的SCPClient类,这个类实现了scp命令功能. 下面的代码包含了传输单个文件和传输目录的功能: package com.doctor.ganymed_ssh2; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io

自动远程登录执行命令

1.自动登录问题,在不考虑秘钥文件情况下想登录远程设备,必须提供ip地址,用户名和密码三个信息,通过telnet或ssh进行登录,可在telnet或ssh的命令中并未找到可指定password的地方. C:\>telnet -h telnet [-a][-e escape char][-f log file][-l user][-t term][host [port]] -a      企图自动登录.除了用当前已登陆的用户名以外,与 -l 选项相同. -e      跳过字符来进入 telnet

Ganymed SSH-2 java执行远程linux机器命令工具

Ganymed SSH2 for Java is a library which implements the SSH-2 protocol in pure Java(tested on J2SE 1.4.2 and 5.0). It allows one to connect to SSH servers from withinJava programs. It supports SSH sessions (remote command execution and shell access),

Python脚本远程批量执行命令

摘要 本文主要写用python脚本远程连接多台服务器,然后批量执行命令,最终返回命令执行结果. 这个可以说是Ansible,Puppet等工具的最简单的雏形. 做运维的同学应该都知道的. 正文 multi_task.py #_*_coding:utf-8_*_ import  multiprocessing import paramiko import getpass import ConfigParser class MultiTask(object):     '''handles all 

jenkins 执行ssh 远程linux执行命令

1.远程机器编写脚本: 脚本名称为: /app/jboss/jboss-as/logs/ALL_SERVICE_STOP.sh 功能为:停止某个服务器某个目录下面的所有应用 #!/bin/bash path=/app/jboss/jboss-as/logs for instance in `ls $path|grep ".*.sh"|grep -v ALL_SERVICE_STOP.sh|xargs`;do cd $path ./$instance stop done 2.2台linu

python利用paramiko连接远程服务器执行命令

python中的paramiko模块是用来实现ssh连接到远程服务器上的库,在进行连接的时候,可以用来执行命令,也可以用来上传文件. 1.得到一个连接的对象 在进行连接的时候,可以使用如下的代码: def connect(host): 'this is use the paramiko connect the host,return conn' ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddP

远程ssh执行命令时提示找不到命令

最开始的时候碰到这种问题,是在hadoop003上配置了jdk1.8, 在hadoop002上执行ssh hadoop003 java -version提示没有命令,先ssh hadoop003然后执行java -version则没有问题后来执行分发脚本时也碰到过这种问题,如果分步执行,先ssh到主机,然后执行命令就没有问题,然而直接ssh + 主机 + 命令就会报错,百度之后发现是ssh远程执行命令时加载的环境文件是~/.bashrc.所以解决的思路就是在~/.bashrc中添加需要的环境变量

expect批量同步或执行命令工具

expect脚本同步文件 我们知道主机间传输一个文件受网络.文件大小和磁盘读写速率的影响,在传输一个文件时不可能一下子马上传输到对方,但是使用expect脚本的过程中,值得注意的是在脚本结尾以expect eof结束整个脚本,它的作用是当脚本内涉及到有文件传输时,会让文件传输完成后再彻底结束掉脚本进程,这样会让文件能够成功传输到对方主机上.expect若使用exit或者没有eof这个选项,那么在执行脚本时,expect不管你是否有文件正在传输,当脚本内容执行完成后直接结束掉自己的进程,这样就会造

使用paramiko模块在远程服务器执行命令

脚本如下: # cat myssh.py  #!/usr/bin/env python import paramiko hostname = '192.168.56.101' port     = 22 username = 'root' password = '111111' if __name__ == "__main__":     paramiko.util.log_to_file('paramiko.log')     s = paramiko.SSHClient()