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. 怎么在網(wǎng)頁中設(shè)置圖片進(jìn)行左右滑動(dòng)2. shell - Update query wrong in MySQL3. javascript - 新浪微博網(wǎng)頁版的字?jǐn)?shù)限制是怎么做的4. node.js - mysql如何通過knex查詢今天和七天內(nèi)的匯總數(shù)據(jù)5. mysql 插入數(shù)值到特定的列一直失敗6. Python從URL中提取域名7. 360瀏覽器與IE瀏覽器有何區(qū)別???8. javascript - 用jsonp抓取qq音樂總是說回調(diào)函數(shù)沒有定義9. python - 在使用Pycharm時(shí)經(jīng)常看到如下的樣式,小括號(hào)里紅色的部分是什么意思呢?10. python 合并dict
