package com.wz.test;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import org.apache.commons.net.telnet.TelnetClient;
public class WindowShell {
private TelnetClient telnet;
private InputStream in; // 输入流,接收返回信息
private PrintStream out; // 向服务器写入 命令
private char prompt = '>'; //结束标识字符
private String pwdString;
public WindowShell(String termtype,String ip, int port, String user, String password, int timeout) throws Exception{
telnet = new TelnetClient(termtype);
telnet.setConnectTimeout(timeout);
telnet.connect(ip, port);
in = telnet.getInputStream();
out = new PrintStream(telnet.getOutputStream());
this.pwdString = "password";
login(user, password);
}
/**
* 登录到目标主机
* @param ip
* @param port
* @param username
* @param password
*/
public void login(String user, String password){
readUntil("login:");
write(user);
readUntil(pwdString+":");
write(password);
readUntil(prompt + "");
}
/**
* 读取分析结果
*
* @param pattern 匹配到该字符串时返回结果
* @return
*/
public String readUntil(String pattern) {
StringBuffer sb = new StringBuffer();
char lastChar = pattern.charAt(pattern.length() - 1);
try {
char ch = (char) in.read();
while (ch != -1) {
sb.append(ch);
if (ch == lastChar && sb.toString().endsWith(pattern)) {
return sb.toString();
}
ch = (char) in.read();
}
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
/**
* 写操作
* @Title write
* @author Administrator
* @param value
* @return void
*/
public void write(String value) {
try {
out.println(value);
out.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 发送命令,返回执行结果
*
* @param command
* @return
*/
public String sendCommand(String command) {
try {
write(command);
return readUntil(prompt + "");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 关闭连接
*/
public void disConnect(){
try {
if(telnet != null) {
telnet.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
System.out.println("启动Telnet...");
String ip = "192.168.1.118";
int port = 23;
String user = "Administrator";
String password = "wz";
int timeout = 5000;
try {
WindowShell telnet = new WindowShell("VT220",ip,port,user,password,timeout);
String rs = telnet.sendCommand("ipconfig");
System.out.println(new String(rs.getBytes("ISO-8859-1"),"GBK"));
telnet.disConnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
commons-net