java使用telnet調(diào)用遠(yuǎn)程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(); }}/** * 向目標(biāo)發(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();}
}
運(yùn)行后報(bào)錯(cuò)如下:這樣應(yīng)該如何解決呢?
問題解答
回答1:因?yàn)檫B接被拒絕了,你先試試本地telnet能不能連上去?
相關(guān)文章:
1. android - webview 自定義加載進(jìn)度條2. 為什么我ping不通我的docker容器呢???3. javascript - 微信小程序限制加載個(gè)數(shù)4. linux - openSUSE 上,如何使用 QQ?5. mysql - 怎么讓 SELECT 1+null 等于 16. python 怎樣用pickle保存類的實(shí)例?7. 并發(fā)模型 - python將進(jìn)程池放在裝飾器里為什么不生效也沒報(bào)錯(cuò)8. 大家好,請(qǐng)問在python腳本中怎么用virtualenv激活指定的環(huán)境?9. linux - 升級(jí)到Python3.6后GDB無法正常運(yùn)行?10. Python中, 仿照經(jīng)典代碼實(shí)現(xiàn)單例, 卻出現(xiàn)了不是單例的的狀態(tài), 代碼哪里出錯(cuò)了 ?
