ホームページ >Java >&#&チュートリアル >JSch がシェル コマンドをリモートで実行する方法
この記事では、JSch を使用してシェル コマンドをリモートで実行する方法を詳しく紹介します。一定の参考値があるので、困っている友達が参考になれば幸いです。

JSch は Java Secure Channel の略称です。 JSch は、SSH2 の純粋な Java 実装です。これにより、SSH サーバーに接続し、ポート転送、X11 転送、ファイル転送などを使用できるようになります。もちろん、その機能を独自のアプリケーションに統合することもできます。フレームワーク jsch は非常に古いフレームワークで、2016 年に更新されましたが、現在は更新されていません。
ChannelExec: 一度に 1 つのコマンドを実行します。通常はこれで十分です。
ChannelShell: 複数のコマンドを実行できます。日常の開発ではあまり使用されません。必要に応じて使用できます。
ChannelExec channelExec = (ChannelExec) session.openChannel("exec");//只能执行一条指令(也可执行符合指令)
ChannelShell channelShell = (ChannelShell) session.openChannel("shell");//可执行多条指令 不过需要输入输出流各コマンドは;で区切ります。注: 各コマンドの実行は、他のコマンドの実行には影響しません。つまり、各コマンドは実行されますが、すべてのコマンドが正常に実行されるという保証はありません。
各コマンドは && で区切ります。注: 前のコマンドが正常に実行されると、次のコマンドが実行されます。これにより、すべてのコマンドが実行された後、実行プロセスが成功することが保証されます。
各コマンドは || で区切ります。注: || は、または、コマンドが正常に実行されるまで、前のコマンドの実行が失敗した後にのみ次のコマンドが実行されることを意味します。
ChannelShell では、ローカル コンピューターで対話型シェルを使用するのと同じように、複数の命令を入力ストリームの形式で実行できます (通常は対象: インタラクティブな使用)。停止したい場合は、次の 2 つの方法があります:
終了コマンドを送信して、この対話が終了したことをプログラムに通知します。 bytes ストリーム内で使用可能なメソッドを使用してデータの合計サイズが取得され、ループで読み取られます。
使用例
<dependency> <groupId>com.jcraft</groupId> <artifactId>jsch</artifactId> <version>0.1.53</version> </dependency>
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 = port;
this.timeout = 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. 获取 ssh session
session = jSch.getSession(username, host, port);
session.setPassword(password);
session.setTimeout(timeout);
session.setConfig("StrictHostKeyChecking", "no");
session.connect(); // 获取到 ssh session
// 2. 通过 exec 方式执行 shell 命令
channelExec = (ChannelExec) session.openChannel("exec");
channelExec.setCommand(cmd);
channelExec.connect(); // 执行命令
// 3. 获取标准输入流
inputStreamReader = new BufferedReader(new InputStreamReader(channelExec.getInputStream()));
// 4. 获取标准错误输入流
errInputStreamReader = new BufferedReader(new InputStreamReader(channelExec.getErrStream()));
// 5. 记录命令执行 log
String line = null;
while ((line = inputStreamReader.readLine()) != null) {
runLog.append(line).append("\n");
}
// 6. 记录命令执行错误 log
String errLine = null;
while ((errLine = errInputStreamReader.readLine()) != null) {
errLog.append(errLine).append("\n");
}
// 7. 输出 shell 命令执行日志
System.out.println("exitStatus=" + channelExec.getExitStatus() + ", openChannel.isClosed="
+ channelExec.isClosed());
System.out.println("命令执行完成,执行日志如下:");
System.out.println(runLog.toString());
System.out.println("命令执行完成,执行错误日志如下:");
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();
}}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);
}} 推奨: 「
Java ビデオ チュートリアル>>
以上がJSch がシェル コマンドをリモートで実行する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。