java控制ssh执行命令
时间: 2023-07-18 09:14:10 浏览: 99
16-17 数据挖掘算法基础 - 分类与回归1(1).ipynb
在Java中可以使用 `JSch` 库来控制SSH执行命令。下面是一个简单的示例代码:
```java
import com.jcraft.jsch.*;
public class SSHCommandExecutor {
public static void main(String[] args) {
String host = "example.com";
String user = "username";
String password = "password";
String command = "ls -la";
try {
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, 22);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command);
channel.setInputStream(null);
((ChannelExec) channel).setErrStream(System.err);
InputStream in = channel.getInputStream();
channel.connect();
byte[] tmp = new byte[1024];
while (true) {
while (in.available() > 0) {
int i = in.read(tmp, 0, 1024);
if (i < 0)
break;
System.out.print(new String(tmp, 0, i));
}
if (channel.isClosed()) {
if (in.available() > 0)
continue;
System.out.println("exit-status: " + channel.getExitStatus());
break;
}
try {
Thread.sleep(1000);
} catch (Exception ee) {
}
}
channel.disconnect();
session.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
这个示例代码连接到SSH主机,执行 `ls -la` 命令,并将命令输出打印到控制台。你可以将 `command` 变量替换为你想要执行的任何命令。
阅读全文