| | |
| | | } |
| | | |
| | | /** |
| | | * 连接到路由器 |
| | | */ |
| | | public boolean connect(String username,String hostname,String password) { |
| | | try { |
| | | JSch jsch = new JSch(); |
| | | session = jsch.getSession(username, hostname, 22); |
| | | session.setPassword(password); |
| | | |
| | | // 设置不进行主机密钥检查 |
| | | 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() { |
| | |
| | | /** |
| | | * 执行路由器命令 |
| | | */ |
| | | public String executeCommand(String command) { |
| | | public String executeCommand(String command,String username,String password,String hostname) { |
| | | if (!isConnected()) { |
| | | if (!connect()) { |
| | | 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; |
| | |
| | | public boolean isConnected() { |
| | | return session != null && session.isConnected(); |
| | | } |
| | | } |
| | | } |