原文参考:
http://www.codeproject.com/Articles/46891/Remote-interactive-SSH-command-in-Java
Remote interactive SSH command in Java
Introduction
This article presents a way to implement a remote connection to a server via SSH (secure shell) and to execute an interactive command through a pseudo terminal in Java.
Background
Programs which implement a remote connection to a server to execute a command via SSH (secure shell) in Java are very common, but most of them can only execute the "exec" command (non interactive cmd, in other words, execute command and hand over the control as soon as the cmd is finished, such as "date" to display the current time, and can not execute "ls' to display the file list under a designated directory (opt/3com/VCX/vcxdata/). This article will show a way to execute those commands, and further, interactive commands (such as "su root", which will claim the password, and we will input the password according to the output we get in real time).
Using the Code
First, import an external jar package sshtools. Then, declare an instance of SshClient
and SessionChannelClient
. You may have noticed that the way to get session output is a little different. We do not declare an object of ChannelOutputStream
; instead, an object of SessionOutputReader
, a point to which I will return.
import com.sshtools.j2ssh.SshClient; import com.sshtools.j2ssh.authentication.PasswordAuthenticationClient; import com.sshtools.j2ssh.session.SessionChannelClient; import com.sshtools.j2ssh.session.SessionOutputReader; import com.sshtools.j2ssh.transport.IgnoreHostKeyVerification;
As we are going to login to the 3com VCX server through SSH, the server IP, user name, and password are required, and set as shown below:
final private String username = "root"; final private String password = "pvadmin"; final private String hostname = "172.31.50.102"; private int outputPos = 0 ;
After executing the command, we get the output as a string. The previous output will be included in the current string to avoid the output being displayed over and over. We set outputPos
as the offset from where the output will be displayed.
ssh = new SshClient(); try{ ssh.connect(hostname, new IgnoreHostKeyVerification());
Create an SSH client to connect to server via SSH, and ignore the host key verification.
PasswordAuthenticationClient pwd = new PasswordAuthenticationClient(); pwd.setUsername(username); pwd.setPassword(password); int result = ssh.authenticate(pwd);
The result must be 4; otherwise, it means the SSH connection is not set up properly.
if (result == 4) { logCat.info("Connected to host"); session = ssh.openSessionChannel(); sor = new SessionOutputReader(session);Open a session channel after connecting to the server successfully, and create an instance of the session output reader of the session.
if (session.requestPseudoTerminal("gogrid",80,24, 0 , 0, ""))
Create a pseudo terminal to connect to the server. The terminal type could be dumb, xterm, gogrid, vt100, vt220, vt320 etc., but I strongly recommend to choose "gogrid", for the others will result in confusing characters.
Here is the the prototype of the requested pseudo terminal:
boolean requestPseudoTerminal(String term, int cols, int rows, int width, int height, String modes) if (session.startShell()) { in = (session.getInputStream()); logCat.info(in); out = session.getOutputStream(); out.write("cd opt/3com/vcx/vcxdata/\n".getBytes()); out.write("ls\n".getBytes());
If it succeeds in starting the shell, execute the following command: "cd /opt/3com/vcx/vcxdata/". Then, "ls" to display the file list under that directory.
Thread.currentThread().sleep(1000*2); String answer = null; String aux = null; aux = sor.getOutput(); answer = aux.substring(outputPos); outputPos = aux.length(); logCat.info(answer);
After executing the command, check the output.
Similarly, we can execute interactive commands according to the last output prompt of the server in real time. For example, we get the cworks privilege, then we want to get back to the root privilege using the "su root" command, and the password prompt will be claimed. We check the output, and when we get the password prompt, we input the password.
out.write("su cworks\n".getBytes()); // input command su cworks out.write("su root\n".getBytes()); // then input command su root which will claim password Thread.currentThread().sleep(1000*2); //verify what we have got String answer = null; String aux = null; aux = sor.getOutput(); // get the output in real time answer = aux.substring(outputPos); outputPos = aux.length(); logCat.info(answer); String str[] = answer.split("\n"); String prompt = str[str.length-1]; // get the last prompt prompt = prompt.trim(); if (prompt.contains("Password:")) // if the last prompt is "password { // then we input password. out.write("pvadmin\n".getBytes()); }
And again, check what we have got this time:
Thread.currentThread().sleep(1000*2); aux = sor.getOutput(); answer = aux.substring(outputPos); logCat.info(answer);
Thanks to SessionOutputReader
, we can read the output stream of the session in real time. So, we can decide what command we should input according to the output prompt of the server, which is the very essence of being interactive.
Points of Interest
I will be glad if this is helpful to you. And thank you for your advice, which helped me make this article better.
Reference: http://upcommons.upc.edu/pfc/bitstream/2099.1/3790/1/53848-1.pdf.
License
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
相关推荐
本篇将详细介绍两种主要的Java连接Linux的方式,并结合`CommandExecutor`这一可能的工具或类库进行讨论。 ### 1. 使用Java的Runtime类执行命令 `Runtime.getRuntime().exec()`方法是Java内置的一种执行外部命令的...
4. **建立通道**:通过`Session`创建一个`Channel`,通常是`ChannelShell`或`ChannelExec`,前者提供一个交互式的shell,后者用于执行命令。 5. **执行命令**:对于`ChannelExec`,调用`setCommand()`方法指定要执行...
2. **JShell(REPL)**:引入了一个命令行工具,用于交互式地测试和学习Java代码,提高了开发者的生产力。 3. **进程API(JEP 208)**:提供了新的API来管理操作系统进程,允许开发者更方便地控制和监控外部进程。 4...
"javascript"和"html5"则是Web开发中的关键技术,通常用于构建交互式前端应用,可能与SAP JCo一起使用来构建Web应用程序,这些应用可以与后端的SAP系统进行数据交互。 压缩包内的"SIGNATURE.SMF"文件可能是签名文件...
Java是广泛使用的编程语言,Java开发者常常需要通过Java连接Redis来实现数据交互。 本资源包“java连接Redis资源包(最新)”提供了适用于Windows和Linux环境的Redis安装文件,确保无论你在哪种操作系统上,都能...
而"Java Call Expect Script.doc"可能讲述了如何使用Java结合`expect`脚本进行交互式进程控制。`expect`是一个Unix/Linux工具,能自动响应交互式程序,常用于自动化SSH登录和脚本操作。 文件"Process Search.doc...
在Java中,Swing提供了丰富的组件库,如按钮、文本框、菜单等,使得开发者能够构建功能完善的交互式应用。Swing是Java Foundation Classes (JFC)的一部分,完全由纯Java编写,因此具有跨平台的特性。 本项目“java...
`sudo`命令要求在交互式TTY上运行,以防止非交互式的恶意脚本滥用权限。而在SSH登录后手动启动和重启Tomcat,由于这时的连接有TTY(通常是pts/n),`sudo`就可以正常工作了。 为了解决这个开机启动时无法使用`sudo`...
SFTP(SSH File Transfer Protocol)是一种安全文件传输协议,它为...此外,本文还提到了其他认证方式,例如password认证,键盘交互式认证和GSS-API认证,但未做详细讨论。有兴趣的读者可以通过查阅相关资料深入学习。
用户可以通过参数传递变量,实现交互式编程。默认情况下,新创建的文件没有执行权限,需要通过chmod命令添加。shell还可以创建子shell来运行脚本,确保主shell环境的完整性。 网络连接在任何计算机中都至关重要。在...
支持在Web浏览器中运行Java Applets,让用户可以在网页中体验基于Java技术的交互式内容。 7. **IBM Java ALSA支持** - `java-1.6.0-ibm-alsa-1.6.0.16.30-1jpp.i386.rpm` 提供了对Advanced Linux Sound ...
SAP GUI 750 for Java Rev1是一款专为Linux用户设计的SAP图形用户界面,它基于Java技术,提供了一种交互式的方式与SAP系统进行连接和操作。这款软件的发布版本为Rev1,已经过在Ubuntu操作系统上的严格测试,确保了其...
WebSocket4J 是一个用 Java 实现的 WebSocket 协议的类库,可使用 Java 来构建交互式 Web 应用。WebSocket4J 并未实现客户端通讯协议,所以不能用它来连接 WebSocket 服务器。 Struts验证码插件 JCaptcha4Struts2 ...
在 OS X 和 Linux 中,PTY 常用于创建交互式 shell 或运行需要终端接口的程序。而在 Windows 系统中,由于原生不支持 PTY,JediTerm 提供了这一功能,使得开发者能够在 Windows 平台上享受类似 Unix 环境下的终端...
8. **AJAX (Asynchronous JavaScript and XML)**:是一种创建交互式Web应用程序的技术,通过在后台与服务器交换数据并局部更新页面,实现了页面的无刷新更新。 9. **EasyUI**:是一个基于jQuery的前端框架,用于...
- **命令行客户端**:Redis自带的命令行工具`redis-cli`,可用于交互式操作Redis数据库,执行各种读写操作。 - **图形界面工具**:如`Redis Desktop Manager`,提供跨平台的图形界面,方便可视化管理Redis实例。 ...
使用`ij`工具,这是JavaDB提供的一个交互式SQL命令行客户端。在命令行中输入`ij`,然后执行SQL命令`CREATE DATABASE mydatabase;`,这将在默认位置创建一个名为`mydatabase`的新数据库。 7. **连接数据库**: ...
- 安装过程中会有各种交互式提示,如地理位置、语言、时区、分区等,根据自身需求进行选择。 2. **JDK 1.5的安装**: - JDK通常以二进制或RPM包的形式提供。在这个例子中,我们使用的是RPM包。 - 将JDK安装包...
2. "Java+3D交互式三维图形编程.pdf" - 这份PDF可能涵盖了使用Java进行3D图形编程的知识,可能包括Java 3D API的介绍、场景图的概念、如何创建和操纵3D对象、光照和纹理处理,以及如何实现用户交互等。Java 3D提供了...
这个"expect所需的全部jar包"包含了 Expect 源码包和所有必要的Java库,使得开发人员能够在Java程序中方便地执行Linux交互式命令。 Expect本身是用Tcl语言编写的,但通过Expect4j这样的Java库,我们可以将它的功能...