62,620
社区成员
发帖
与我相关
我的任务
分享import java.io.*;
import org.apache.commons.net.telnet.*;
public class ApacheTelnet {
public ApacheTelnet() {
telnet = new TelnetClient("VT220");
promptText = prompt;
connetionStatus = false;
}
public boolean Connect(String ip, int port, String user, String password) {
try {
if (connetionStatus == false) {
telnet.connect(ip, port);
in = telnet.getInputStream();
out = new PrintStream(telnet.getOutputStream());
login(user, password);
connetionStatus = true;
return true;
} else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public void login(String user, String password) {
readUntil("login:");
write(user);
readUntil("password:");
write(password);
readUntil(prompt);
}
public void write(String value) {
try {
out.println(value);
out.flush();
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
}
public boolean disconnect() {
try {
if (connetionStatus == true) {
telnet.disconnect();
connetionStatus = false;
return true;
} else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public String readUntil(String pattern) {
try {
StringBuffer sb = new StringBuffer();
// boolean found = false;
char ch = (char) in.read();
sb.append(ch);
while (sb.toString().endsWith(pattern) != true) {
ch = (char) in.read();
sb.append(ch);
}
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public String sendCommand(String command) {
try {
getCurrentDir();
write(command);
returnText = readUntil(promptText);
returnText = isoToGbk(returnText);
returnText = returnText.substring(command.length() + 2,
returnText.length() - promptText.length());
return returnText;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public void getCurrentDir() {
try {
write(" ");
promptText = readUntil(prompt);
promptText = isoToGbk(promptText);
promptText = promptText.substring(3, promptText.length());
} catch (Exception e) {
e.printStackTrace();
}
}
public static String isoToGbk(String para) {
try {
return new String(para.getBytes("ISO-8859-1"), "GBK");
} catch (Exception e) {
return "";
}
}
public static String gbkToIso(String para) {
try {
return new String(para.getBytes("GBK"), "ISO-8859-1");
} catch (Exception e) {
return "";
}
}
private TelnetClient telnet;
private InputStream in;
private PrintStream out;
private String promptText;
private String returnText;
private String prompt = ">";
private boolean connetionStatus;
}