
Java可以通过SSH协议远程连接Linux服务器,然后使用JSch库或者Apache Commons Net库来执行远程Linux命令。以下是一个使用JSch库的示例代码:
- import com.jcraft.jsch.*;
-
- public class RemoteCommandExecutor {
- private String host;
- private String user;
- private String password;
-
- public RemoteCommandExecutor(String host, String user, String password) {
- this.host = host;
- this.user = user;
- this.password = password;
- }
-
- public void executeCommand(String command) throws JSchException {
- JSch jsch = new JSch();
- Session session = jsch.getSession(user, host, 22); // 默认SSH端口号为22
- session.setConfig("StrictHostKeyChecking", "no"); // 不进行公钥验证
- session.setPassword(password);
- session.connect();
- ChannelExec channel = (ChannelExec) session.openChannel("exec");
- channel.setCommand(command);
- channel.setInputStream(null);
- channel.setErrStream(System.err);
- channel.connect();
- channel.disconnect();
- session.disconnect();
- }
-
- public static void main(String[] args) throws JSchException {
- RemoteCommandExecutor executor = new RemoteCommandExecutor("192.168.0.1", "username", "password");
- executor.executeCommand("ls -l");
- }
- }
该示例通过构造方法传入服务器地址、用户名和密码,然后在executeCommand方法中执行传入的命令。在执行命令之前,需要建立一个SSH会话,并且打开一个执行命令的通道,最后关闭通道和会话。
注意事项: