我需要远程连接 Linux 然后执行命令
时间: 2024-09-28 18:12:45 浏览: 30
Java远程连接Linux服务器并执行命令及上传文件功能
5星 · 资源好评率100%
远程连接Linux并执行命令通常使用SSH(Secure Shell)协议。在Java中,你可以使用Jsch(Java Secure Shell)库或其他支持SSH的功能。以下是一个基本步骤:
1. **添加依赖** (如果你使用的是Apache Commons Net库):
对于Apache Commons Net,你需要引入`commons.net.*`包,或者对于更现代的选择,如JSch,你需要Maven或Gradle添加相应依赖。
2. **使用JSch(Java Secure Shell)**:
```java
import com.jcraft.jsch.*;
JSch jsch = new JSch();
Session session = null;
try {
session = jsch.getSession(user, host, port); // replace user, host and port with your credentials
session.setPassword(password); // replace password with your actual password or use key-based authentication
session.setConfig("StrictHostKeyChecking", "no"); // disable host key checking for development, change to "yes" in production
session.connect();
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command); // replace command with the shell command you want to execute
channel.connect(); // execute the command
InputStream in = channel.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
int exitCode = channel.getExitStatus();
if (exitCode == 0) {
System.out.println("Command executed successfully.");
} else {
System.err.println("Execution failed with exit code: " + exitCode);
}
} finally {
if (session != null) {
session.disconnect();
}
}
```
阅读全文