Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to execute Shell commands remotely by Java JSch

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "how Java JSch executes Shell commands remotely". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how Java JSch executes Shell commands remotely".

Introduction to JSch

JSch is the abbreviation of Java Secure Channel. JSch is a pure Java implementation of SSH2. It allows you to connect to a SSH server and can use port forwarding, X11 forwarding, file transfer, etc., of course, you can also integrate its functions into your own applications. Framework jsch very old framework, updated to 2016, is not updated now.

JSch uses shell to execute commands, and there are two ways

ChannelExec: execute one command at a time, and this is usually enough for us.

ChannelShell: you can execute multiple commands, but you don't usually use much for development. Come according to your needs.

ChannelExec channelExec = (ChannelExec) session.openChannel ("exec"); / / only one instruction can be executed (conformance instruction can also be executed) ChannelShell channelShell = (ChannelShell) session.openChannel ("shell"); / / multiple instructions can be executed but input and output streams are required

1. ChannelExec

Use between each command; separate. Description: the execution of each command will not affect the execution of other commands. In other words, each command is executed, but there is no guarantee that every command will be executed successfully.

Each command is separated by & &. Description: if the previous command is executed successfully, the following command will be executed. This ensures that after all commands are executed, the execution process is successful.

Use "|" between each command. Description: | | Yes or, only if the previous command fails to execute the next command, until a successful command is executed.

2. ChannelShell

For ChannelShell, multiple instructions can be executed in the form of an input stream, just like using interactive shell on the local computer (which is usually used for interactive use). There are two ways to stop:

Send an exit command to tell the program that the interaction is over

Use the available method in the byte stream to get the total size of the data, and then loop through it.

Use the example

1. Introduce pom dependency

Com.jcraft jsch 0.1.53

2. Jsch usage example

A Shell utility class is encapsulated here, which is used to execute shell commands. The specific usage details are described in the code comments, which can be copied and used directly. The code is as follows:

Package org.example.shell;/** * Created by qianghaohao on 2021-3-28 * / import com.jcraft.jsch.ChannelExec;import com.jcraft.jsch.JSch;import com.jcraft.jsch.Session;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;/** * @ description: * @ author: qianghaohao * @ time: 2021-3-28 * / public class Shell {private String host; private String username; private String password; private int port = 22 Private int timeout = 60 * 60 * 1000; public Shell (String host, String username, String password, int port, int timeout) {this.host = host; this.username = username; this.password = password; this.port = timeout;} public Shell (String host, String username, String password) {this.host = host; this.username = username This.password = password;} public String execCommand (String cmd) {JSch jSch = new JSch (); Session session = null; ChannelExec channelExec = null; BufferedReader inputStreamReader = null; BufferedReader errInputStreamReader = null; StringBuilder runLog = new StringBuilder ("); StringBuilder errLog = new StringBuilder ("); try {/ / 1. Get ssh session session = jSch.getSession (username, host, port); session.setPassword (password); session.setTimeout (timeout); session.setConfig ("StrictHostKeyChecking", "no"); session.connect (); / / get ssh session / / 2. Execute the shell command channelExec = (ChannelExec) session.openChannel ("exec"); channelExec.setCommand (cmd); channelExec.connect (); / / execute the command / / 3 through exec. Get the standard input stream inputStreamReader = new BufferedReader (new InputStreamReader (channelExec.getInputStream (); / / 4. Get the standard error input stream errInputStreamReader = new BufferedReader (new InputStreamReader (channelExec.getErrStream (); / / 5. Record the command log String line = null; while ((line = inputStreamReader.readLine ())! = null) {runLog.append (line) .append ("\ n");} / / 6. Record command execution error log String errLine = null; while ((errLine = errInputStreamReader.readLine ())! = null) {errLog.append (errLine) .append ("\ n");} / / 7. Output shell command execution log System.out.println ("exitStatus=" + channelExec.getExitStatus () + ", openChannel.isClosed=" + channelExec.isClosed ()); System.out.println ("command execution completed, execution log is as follows:"); System.out.println (runLog.toString ()) System.out.println ("Command execution completed, execution error log is as follows:"); System.out.println (errLog.toString ());} catch (Exception e) {e.printStackTrace ();} finally {try {if (inputStreamReader! = null) {inputStreamReader.close () } if (errInputStreamReader! = null) {errInputStreamReader.close ();} if (channelExec! = null) {channelExec.disconnect ();} if (session! = null) {session.disconnect () } catch (IOException e) {e.printStackTrace ();}} return runLog.toString ();}}

The above tool classes use:

Package org.example;import org.example.shell.Shell;/** * Hello world! * * / public class App {public static void main (String [] args) {String cmd = "ls-1"; Shell shell = new Shell ("192.168.10.10", "ubuntu", "11111"); String execLog = shell.execCommand (cmd); System.out.println (execLog);} points to pay attention to

If you need to execute a command in the background, you can't execute it directly by + &, which doesn't work in JSch. You need to write it in the format: > / dev/null 2 > & 1 &. For example, to execute sleep 60 in the background, it needs to be written as sleep 60 > / dev/null 2 > & 1

Thank you for your reading, the above is the content of "how Java JSch executes Shell commands remotely". After the study of this article, I believe you have a deeper understanding of how Java JSch executes Shell commands remotely, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report