| | |
| | | @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() { |
| | | // 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 String executeCommand(String command,String username,String password,String hostname) { |
| | | if (!isConnected()) { |
| | | if (!connect(username,hostname,password)) { |
| | | return null; |
| | | } |
| | | // if (!isConnected()) { |
| | | // if (!connect(username,hostname,password)) { |
| | | // return null; |
| | | // } |
| | | // } |
| | | if (!connect(username,hostname,password)) { |
| | | return null; |
| | | } |
| | | |
| | | try { |
| | |
| | | |
| | | reader.close(); |
| | | channel.disconnect(); |
| | | disconnect(); |
| | | return output.toString(); |
| | | } catch (Exception e) { |
| | | System.err.println("执行命令失败: " + e.getMessage()); |