1
我們想要使用telnet在Windows Server 2008/Windows 7上執行一些命令。由於每次登錄和運行大約50個命令都是單調乏味的,所以我在谷歌中搜索並精通到Apache公用程序,我找到了一個例子。Telnet Apache Commons NET打印垃圾字符
它的工作原理,但它打印一些垃圾字符(我認爲這是Windows的字符編碼的一些問題,我是新來的)。
package com.kiran.telnet;
import org.apache.commons.net.telnet.TelnetClient;
import java.io.InputStream;
import java.io.PrintStream;
public class AutomatedTelnetClient {
private TelnetClient telnet = new TelnetClient();
private InputStream in;
private PrintStream out;
private String prompt = ">";
public AutomatedTelnetClient(String server, String user, String password) {
try {
// Connect to the specified server
telnet.connect(server, 23);
// Get input and output stream references
in = telnet.getInputStream();
out = new PrintStream(telnet.getOutputStream(), true);
// Log the user on
readUntil("login: ");
write(user);
readUntil("password: ");
write(password);
// Advance to a prompt
readUntil(prompt + " ");
} catch (Exception e) {
e.printStackTrace();
}
}
public void su(String password) {
try {
write("su");
readUntil("Password: ");
write(password);
prompt = ">";
readUntil(prompt + " ");
} catch (Exception e) {
e.printStackTrace();
}
}
public String readUntil(String pattern) {
try {
char lastChar = pattern.charAt(pattern.length() - 1);
StringBuffer sb = new StringBuffer();
boolean found = false;
char ch = (char) in.read();
while (true) {
System.out.print(ch);
sb.append(ch);
if (ch == lastChar) {
if (sb.toString().endsWith(pattern)) {
return sb.toString();
}
}
ch = (char) in.read();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public void write(String value) {
try {
out.println(value);
out.flush();
System.out.println(value);
} catch (Exception e) {
e.printStackTrace();
}
}
public String sendCommand(String command) {
try {
write(command);
return readUntil(prompt);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public void disconnect() {
try {
telnet.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
AutomatedTelnetClient telnet = new AutomatedTelnetClient(
"127.0.0.1", "Kiran", "artha");
System.out.println("Got Connection...");
telnet.sendCommand("hostname");
//telnet.sendCommand("ipconfig");
//telnet.sendCommand("ps -ef ");
//System.out.println("run command");
//telnet.sendCommand("ls ");
//System.out.println("run command 2");
telnet.disconnect();
System.out.println("DONE");
} catch (Exception e) {
e.printStackTrace();
}
}
}
輸出,而我運行是這樣的: 歡迎使用Microsoft Telnet服務
login: Kiran
Kiran
password: artha
[1;1H*=============================================================== [2;1HMicrosoft Telnet Server. [3;1H*=============================================================== [4;1HC:\Users\Kiran> Got Connection...
hostname
[5;1H[K[6;1H[K[7;1H[K[8;1H[K[9;1H[K[10;1H[K[11;1H[K[12;1H[K[13;1H[K[14;1H[K[15;1H[K[16;1H[K[17;1H[K[18;1H[K[19;1H[K[20;1H[K[21;1H[K[22;1H[K[23;1H[K[24;1H[K[25;1H[K[4;16Hhostname[5;1HKiran-PC[7;1HC:\Users\Kiran>DONE
而 「[」
任何幫助,對此人之前一些ESC字符。
謝謝。
謝謝,它爲我工作:-) – kiranm516