kongdeqiang
2025-12-02 55f4c8cda0f426e3a8d31908018a6b9c890bc006
src/main/java/com/wgcloud/service/RouterConnectionService.java
@@ -14,25 +14,38 @@
@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 boolean connect() {
    public boolean connect(String username,String hostname,String password) {
        try {
            JSch jsch = new JSch();
            session = jsch.getSession(routerUsername, routerHost, 22);
            session.setPassword(routerPassword);
            session = jsch.getSession(username, hostname, 22);
            session.setPassword(password);
            // 设置不进行主机密钥检查
            Properties config = new Properties();
@@ -59,18 +72,19 @@
    /**
     * 执行路由器命令
     */
    public String executeCommand(String command) {
        if (!isConnected()) {
            if (!connect()) {
                return null;
            }
    public String executeCommand(String command,String username,String password,String hostname) {
//        if (!isConnected()) {
//            if (!connect(username,hostname,password)) {
//                return null;
//            }
//        }
        if (!connect(username,hostname,password)) {
            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;
@@ -81,6 +95,7 @@
            reader.close();
            channel.disconnect();
            disconnect();
            return output.toString();
        } catch (Exception e) {
            System.err.println("执行命令失败: " + e.getMessage());
@@ -95,4 +110,4 @@
    public boolean isConnected() {
        return session != null && session.isConnected();
    }
}
}