package com.wgcloud.service;
|
|
import com.jcraft.jsch.ChannelExec;
|
import com.jcraft.jsch.JSch;
|
import com.jcraft.jsch.JSchException;
|
import com.jcraft.jsch.Session;
|
import org.springframework.beans.factory.annotation.Value;
|
import org.springframework.stereotype.Service;
|
|
import java.io.BufferedReader;
|
import java.io.InputStreamReader;
|
import java.util.Properties;
|
|
@Service
|
public class RouterConnectionService {
|
|
@Value("${router.host}")
|
private String routerHost;
|
|
@Value("${router.username}")
|
private String routerUsername;
|
|
@Value("${router.password}")
|
private String routerPassword;
|
|
private Session session;
|
|
/**
|
* 连接到路由器
|
*/
|
public boolean connect() {
|
try {
|
JSch jsch = new JSch();
|
session = jsch.getSession(routerUsername, routerHost, 22);
|
session.setPassword(routerPassword);
|
|
// 设置不进行主机密钥检查
|
Properties config = new Properties();
|
config.put("StrictHostKeyChecking", "no");
|
session.setConfig(config);
|
|
session.connect(5000); // 5秒超时
|
return true;
|
} catch (JSchException e) {
|
System.err.println("连接路由器失败: " + e.getMessage());
|
return false;
|
}
|
}
|
|
/**
|
* 断开连接
|
*/
|
public void disconnect() {
|
if (session != null && session.isConnected()) {
|
session.disconnect();
|
}
|
}
|
|
/**
|
* 执行路由器命令
|
*/
|
public String executeCommand(String command) {
|
if (!isConnected()) {
|
if (!connect()) {
|
return null;
|
}
|
}
|
|
try {
|
ChannelExec channel = (ChannelExec) session.openChannel("exec");
|
channel.setCommand(command);
|
channel.connect();
|
|
BufferedReader reader = new BufferedReader(new InputStreamReader(channel.getInputStream()));
|
StringBuilder output = new StringBuilder();
|
String line;
|
|
while ((line = reader.readLine()) != null) {
|
output.append(line).append("\n");
|
}
|
|
reader.close();
|
channel.disconnect();
|
return output.toString();
|
} catch (Exception e) {
|
System.err.println("执行命令失败: " + e.getMessage());
|
disconnect(); // 执行失败时断开连接,下次重连
|
return null;
|
}
|
}
|
|
/**
|
* 检查连接状态
|
*/
|
public boolean isConnected() {
|
return session != null && session.isConnected();
|
}
|
}
|