java使用telnet調(diào)用遠程cmd命令
問題描述
代碼如下:
import java.io.IOException;import java.io.InputStream;import java.io.PrintStream;import java.io.UnsupportedEncodingException;import java.net.SocketException;
import org.apache.commons.net.telnet.TelnetClient;
public class WindowsShell {
TelnetClient telnet = new TelnetClient('VT220');InputStream in;PrintStream out;String prompt = '>';public WindowsShell(String ip, int port, String user, String password) { try {telnet.connect(ip, port);in = telnet.getInputStream();out = new PrintStream(telnet.getOutputStream());login(user, password); } catch (SocketException e) {// TODO Auto-generated catch blocke.printStackTrace(); } catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace(); }}
/** * 讀取分析結(jié)果 * * @param pattern * @return */public String readUntil(String pattern) { try {char lastChar = pattern.charAt(pattern.length() - 1);StringBuffer sb = new StringBuffer();char ch = (char) in.read();while (true) { sb.append(ch); if (ch == lastChar) {if (sb.toString().endsWith(pattern)) { return sb.toString();} } ch = (char) in.read();
//System.out.print(ch);
} } catch (Exception e) {e.printStackTrace(); } return null;}/** * 寫操作 * * @param value */public void write(String value) { try {out.println(value);out.flush(); } catch (Exception e) {e.printStackTrace(); }}/** * 向目標發(fā)送命令字符串 * * @param command * @return */public String sendCommand(String command) { try {write(command);return readUntil(prompt + ''); } catch (Exception e) {e.printStackTrace(); } return null;} /** * 登錄 * * @param user * @param password */public void login(String user, String password) { // read()Until('login:'); readUntil('login:'); write(user); readUntil('password:'); write(password); readUntil(prompt + '');}/** * 關(guān)閉連接 */public void disconnect() { try {telnet.disconnect(); } catch (Exception e) {e.printStackTrace(); }}public static void main(String[] args) {WindowsShell ws = new WindowsShell('192.168.100.100', 23, 'Administrator', '123456');
// System.out.println(ws);
// 執(zhí)行的命令String str = ws.sendCommand('ipconfig');try{ str = new String(str.getBytes('ISO-8859-1'),'GBK');}catch(UnsupportedEncodingException e){ e.printStackTrace();
}
System.out.println(str);ws.disconnect();}
}
運行后報錯如下:這樣應該如何解決呢?
問題解答
回答1:因為連接被拒絕了,你先試試本地telnet能不能連上去?
相關(guān)文章:
1. node.js - webpack-dev-server正常運行,webpack打包卻出錯,怎么辦?2. mysql 5個left關(guān)鍵 然后再用搜索條件 幾千條數(shù)據(jù)就會卡,如何解決呢3. javascript - webpack編譯后的文件不生效,未編譯的文件生效4. android - 哪位大神知道java后臺的api接口的對象傳到前端后輸入日期報錯,是什么情況?求大神指點5. 這是什么情況???6. thinkphp3 count()方法必須加上字段?7. 怎么php怎么通過數(shù)組顯示sql查詢結(jié)果呢,查詢結(jié)果有多條,如圖。我要forsearch里面echo8. 輸入地址報以下截圖錯誤,怎么辦?9. javascript - 項目的公共文件如圖片JS等文件放在 云上,webroot只放jsp文件,怎么將靜態(tài)文件通過配置文件引入,sp求大神指導10. python中return 語句與 分支語句連用問題
