


Detailed introduction to java connecting to the server through ssh to execute shell commands and sample code
This article mainly introduces the detailed explanation and example methods of java connecting to the server through ssh to execute shell commands.
java The detailed explanation of java connecting to the server through ssh to execute shell commands
java connects to the server through ssh to execute shell commands: JSch is a pure Java implementation of SSH2. It allows you to connect to an sshd server, use port forwarding, X11 forwarding, file transfers and more. You can integrate its functionality into your own programs. At the same time, the project also provides a J2ME version for direct connection to the SSHD server on the mobile phone.
SSH is the abbreviation of Secure Shell, a security protocol based on the application layer and transport layer. SSH encrypts all data during the connection and transmission process, and can be used to establish secure connections between different systems or servers. SSH provides two security authentication methods: password-based authentication and key-based authentication. Among them, password-based authentication is relatively simple. As long as you know the user name and password of the remote host, you can log in. Key-based authentication is more troublesome and the connection is more time-consuming, so we will not introduce it in detail here.
There are many clients based on the SSH protocol, such as: PuTTY, OpenSSH, Xshell 4, etc., which can remotely connect to almost all UNIX platforms. At the same time, you can connect to a host through the Linux command line ssh uername@host.
In the project, how to use code to implement SSH and execute Shell script remotely? JSch is the abbreviation of Java Secure Channel. It is a pure Java implementation of SSH2 function. For specific information, please refer to the JSch official website. It allows you to connect to an SSH server and use port forwarding, X11 forwarding, file transfer, etc., and you can also integrate its functionality into your own applications. Before use, you need to download and import the JSch package: jsch-0.1.50.jar.
Sample Program
package com.stormma.demo; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import com.jcraft.jsch.Channel; import com.jcraft.jsch.ChannelExec; import com.jcraft.jsch.JSch; import com.jcraft.jsch.JSchException; import com.jcraft.jsch.Session; public class Shell { //远程主机的ip地址 private String ip; //远程主机登录用户名 private String username; //远程主机的登录密码 private String password; //设置ssh连接的远程端口 public static final int DEFAULT_SSH_PORT = 22; //保存输出内容的容器 private ArrayList<string> stdout; /** * 初始化登录信息 * @param ip * @param username * @param password */ public Shell(final String ip, final String username, final String password) { this.ip = ip; this.username = username; this.password = password; stdout = new ArrayList<string>(); } /** * 执行shell命令 * @param command * @return */ public int execute(final String command) { int returnCode = 0; JSch jsch = new JSch(); MyUserInfo userInfo = new MyUserInfo(); try { //创建session并且打开连接,因为创建session之后要主动打开连接 Session session = jsch.getSession(username, ip, DEFAULT_SSH_PORT); session.setPassword(password); session.setUserInfo(userInfo); session.connect(); //打开通道,设置通道类型,和执行的命令 Channel channel = session.openChannel("exec"); ChannelExec channelExec = (ChannelExec)channel; channelExec.setCommand(command); channelExec.setInputStream(null); BufferedReader input = new BufferedReader(new InputStreamReader (channelExec.getInputStream())); channelExec.connect(); System.out.println("The remote command is :" + command); //接收远程服务器执行命令的结果 String line; while ((line = input.readLine()) != null) { stdout.add(line); } input.close(); // 得到returnCode if (channelExec.isClosed()) { returnCode = channelExec.getExitStatus(); } // 关闭通道 channelExec.disconnect(); //关闭session session.disconnect(); } catch (JSchException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return returnCode; } /** * get stdout * @return */ public ArrayList<string> getStandardOutput() { return stdout; } public static void main(final String [] args) { Shell shell = new Shell("xxx.xxx.xxx.xxx", "username", "password"); shell.execute("uname -s -r -v"); ArrayList<string> stdout = shell.getStandardOutput(); for (String str : stdout) { System.out.println(str); } } }
MyUserInfo
package com.stormma.demo; import com.jcraft.jsch.UserInfo; public class MyUserInfo implements UserInfo { @Override public String getPassphrase() { // TODO Auto-generated method stub System.out.println("MyUserInfo.getPassphrase()"); return null; } @Override public String getPassword() { // TODO Auto-generated method stub System.out.println("MyUserInfo.getPassword()"); return null; } @Override public boolean promptPassphrase(String arg0) { // TODO Auto-generated method stub System.out.println("MyUserInfo.promptPassphrase()"); System.out.println(arg0); return false; } @Override public boolean promptPassword(String arg0) { // TODO Auto-generated method stub System.out.println("MyUserInfo.promptPassword()"); System.out.println(arg0); return false; } @Override public boolean promptYesNo(String arg0) { // TODO Auto-generated method stub' System.out.println("MyUserInfo.promptYesNo()"); System.out.println(arg0); if (arg0.contains("The authenticity of host")) { return true; } return true; } @Override public void showMessage(String arg0) { // TODO Auto-generated method stub System.out.println("MyUserInfo.showMessage()"); } }
The above is the detailed content of Detailed introduction to java connecting to the server through ssh to execute shell commands and sample code. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.
