spring boot 连接Linux 工具类
时间: 2023-10-09 13:10:29 浏览: 40
对于连接Linux的工具类,我们可以使用JSch库。下面是一个连接Linux服务器并执行命令的示例代码:
```
public class SSHUtil {
private String host;
private String username;
private String password;
private JSch jsch;
private Session session;
public SSHUtil(String host, String username, String password) {
this.host = host;
this.username = username;
this.password = password;
jsch = new JSch();
}
public void connect() throws JSchException {
session = jsch.getSession(username, host, 22);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
}
public void disconnect() {
if (session != null) {
session.disconnect();
}
}
public String executeCommand(String command) throws JSchException, IOException {
ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
InputStream in = channelExec.getInputStream();
channelExec.setCommand(command);
channelExec.connect();
StringBuilder result = new StringBuilder();
byte[] buffer = new byte[1024];
while (true) {
while (in.available() > 0) {
int i = in.read(buffer, 0, 1024);
if (i < 0) {
break;
}
result.append(new String(buffer, 0, i));
}
if (channelExec.isClosed()) {
if (in.available() > 0) {
continue;
}
result.append("exit-status: ").append(channelExec.getExitStatus());
break;
}
try {
Thread.sleep(1000);
} catch (InterruptedException ignore) { }
}
channelExec.disconnect();
return result.toString();
}
}
```
你可以通过创建SSHUtil对象,传入服务器地址、用户名和密码来连接Linux服务器,并执行需要的命令。例如,下面是在Linux上执行ls命令的示例代码:
```
public static void main(String[] args) throws JSchException, IOException {
SSHUtil ssh = new SSHUtil("192.168.0.1", "root", "password");
ssh.connect();
String result = ssh.executeCommand("ls");
System.out.println(result);
ssh.disconnect();
}
```
希望这个例子对你有所帮助!