欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 养生 > Java 远程执行服务器上的命令

Java 远程执行服务器上的命令

2025/7/9 4:24:18 来源:https://blog.csdn.net/TalorSwfit20111208/article/details/141969675  浏览:    关键词:Java 远程执行服务器上的命令

在Java中使用JSch库执行远程服务器上的命令是一种常见的做法,特别是在需要自动化运维任务或者进行远程文件操作时。以下是基于Codekru网站提供的示例,展示如何使用JSch库在远程服务器上执行单个或多个命令。

准备工作

首先,确保您的项目中已经包含了JSch库的依赖。如果您使用Maven作为构建工具,可以在pom.xml文件中添加如下依赖:

<dependency><groupId>com.jcraft</groupId><artifactId>jsch</artifactId><version>0.1.55</version>
</dependency>

连接到远程服务器

在执行命令之前,需要先建立与远程服务器的SSH连接。以下是一个简单的连接示例:

import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.JSchException;public class SSHConnectionExample {public static void main(String[] args) {try {JSch jsch = new JSch();String user = "codekru"; // 您的用户名String host = "127.0.0.1"; // 您的远程服务器地址int port = 22; // 默认SSH端口String key = "/path/to/your/privatekey.pem"; // 您的私钥路径jsch.addIdentity(key);Session session = jsch.getSession(user, host, port);session.setConfig("StrictHostKeyChecking", "no");session.setTimeout(15000); // 设置超时时间session.connect();System.out.println("Connected");// 在这里您可以执行其他操作,如执行命令或传输文件session.disconnect(); // 断开连接} catch (JSchException e) {e.printStackTrace();}}
}

执行单个命令

一旦建立了SSH连接,您就可以使用JSch库执行远程命令。以下是一个简单的示例:

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.JSchException;public class ExecuteSingleCommandExample {public static void main(String[] args) {try {JSch jsch = new JSch();String user = "codekru"; // 您的用户名String host = "127.0.0.1"; // 您的远程服务器地址int port = 22; // 默认SSH端口String key = "/path/to/your/privatekey.pem"; // 您的私钥路径jsch.addIdentity(key);Session session = jsch.getSession(user, host, port);session.setConfig("StrictHostKeyChecking", "no");session.setTimeout(15000); // 设置超时时间session.connect();String command = "ls -l"; // 您要执行的命令Channel channel = session.openChannel("exec");((ChannelExec) channel).setCommand(command);channel.setInputStream(null); // 这个方法必须在connect之前调用((ChannelExec) channel).setErrStream(System.err);InputStream inputStream = channel.getInputStream();channel.connect();byte[] byteObject = new byte[10240];while (true) {while (inputStream.available() > 0) {int readByte = inputStream.read(byteObject, 0, 1024);if (readByte < 0)break;String result = new String(byteObject, 0, readByte);System.out.print(result);}if (channel.isClosed())break;}channel.disconnect();System.out.println("Disconnected channel " + channel.getExitStatus());session.disconnect(); // 断开连接} catch (JSchException e) {e.printStackTrace();}}
}

执行多个命令

如果您需要在同一个SSH连接中执行多个命令,可以将这些命令使用分号(;)隔开。以下是一个执行多个命令的示例:

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.JSchException;public class ExecuteMultipleCommandsExample {public static void main(String[] args) {try {JSch jsch = new JSch();String user = "codekru"; // 您的用户名String host = "127.0.0.1"; // 您的远程服务器地址int port = 22; // 默认SSH端口String key = "/path/to/your/privatekey.pem"; // 您的私钥路径jsch.addIdentity(key);Session session = jsch.getSession(user, host, port);session.setConfig("StrictHostKeyChecking", "no");session.setTimeout(15000); // 设置超时时间session.connect();String command = "cd /Users/codekru/jsch-tutorial/; cd ..; ls -l"; // 多个命令Channel channel = session.openChannel("exec");((ChannelExec) channel).setCommand(command);channel.setInputStream(null); // 这个方法必须在connect之前调用((ChannelExec) channel).setErrStream(System.err);InputStream inputStream = channel.getInputStream();channel.connect();byte[] byteObject = new byte[10240];while (true) {while (inputStream.available() > 0) {int readByte = inputStream.read(byteObject, 0, 1024);if (readByte < 0)break;String result = new String(byteObject, 0, readByte);System.out.print(result);}if (channel.isClosed())break;}channel.disconnect();System.out.println("Disconnected channel " + channel.getExitStatus());session.disconnect(); // 断开连接} catch (JSchException e) {e.printStackTrace();}}
}

处理无效命令

当您尝试执行一个无效的命令时,JSch库会捕获错误并将错误信息输出到标准错误流。以下是一个执行无效命令的示例:

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.JSchException;public class HandleInvalidCommandExample {public static void main(String[] args) {try {JSch jsch = new JSch();String user = "codekru"; // 您的用户名String host = "127.0.0.1"; // 您的远程服务器地址int port = 22; // 默认SSH端口String key = "/path/to/your/privatekey.pem"; // 您的私钥路径jsch.addIdentity(key);Session session = jsch.getSession(user, host, port);session.setConfig("StrictHostKeyChecking", "no");session.setTimeout(15000); // 设置超时时间session.connect();String command = "qwerty"; // 无效命令Channel channel = session.openChannel("exec");((ChannelExec) channel).setCommand(command);channel.setInputStream(null); // 这个方法必须在connect之前调用((ChannelExec) channel).setErrStream(System.err);InputStream inputStream = channel.getInputStream();channel.connect();byte[] byteObject = new byte[10240];while (true) {while (inputStream.available() > 0) {int readByte = inputStream.read(byteObject, 0, 1024);if (readByte < 0)break;String result = new String(byteObject, 0, readByte);System.out.print(result);}if (channel.isClosed())break;}channel.disconnect();System.out.println("Disconnected channel " + channel.getExitStatus());session.disconnect(); // 断开连接} catch (JSchException e) {e.printStackTrace();}}
}

在执行无效命令时,控制台将输出错误信息,例如:

connected
bash: qwerty: command not found
Disconnected channel 127

总结

通过上述示例,您可以了解如何使用JSch库在远程服务器上执行单个或多个命令。无论是执行有效的命令还是处理无效命令,都可以按照上述步骤实现。记得在实际使用中替换示例中的占位符为真实的用户名、IP地址、端口号、私钥路径以及命令。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com