封装类 TelnetHandle
import org.apache.commons.net.telnet.TelnetClient;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class TelnetHandle {
private TelnetClient telnetClinet = null;
private InputStream is = null;
private OutputStream os = null;
/**
* 连接远程计算机,连接完成后,获取读取流与发送流
*
* @param ip 远程计算机IP地址
* @param port 远程计算机端口
*/
public void connection(String ip, int port) {
try {
telnetClinet = new TelnetClient();
telnetClinet.connect(ip, port);
is = telnetClinet.getInputStream();
os = telnetClinet.getOutputStream();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取远程计算机返回的信息
*/
public String readTelnetMsg() {
try {
int len = 0;
byte[] b = new byte[1024];
do {
len = is.read(b);
if (len >= 0)
return new String(b, 0, len);
}
while (len >= 0);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 向远端计算机发送指令消息
*
* @param msg 需要传送的指令
**/
public void sendTelnetMsg(String msg) {
byte[] b = msg.getBytes();
try {
os.write(b, 0, b.length);
os.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 查找远端计算机返回的指令中是否包含想要指令
* 一直查找,直到包含,返回true
*/
public boolean findStr(String str) {
for (; ; ) {
String msg = readTelnetMsg();
if(msg==null) return false;
if (msg.indexOf(str) != -1)
return true;
}
}
/**
* 关闭连接,关闭IO
*/
public void close() {
try {
is.close();
os.close();
telnetClinet.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
接口 TelnetService
@Service
public class TelnetService{
public Object AddTelnet(RequestBody RequestBody) throws InterruptedException {
TelnetHandle telnet = new TelnetHandle();
telnet.connection(RequestBody.getIp(), RequestBody.getPort());//登录
if(telnet.findStr("login"))//如果远程计算机返回login字符
telnet.sendTelnetMsg(RequestBody.getUsername()+"\n");//传输用户名,改写你的用户名,该用户名属于TelnetClients组
if(telnet.findStr("Password"))//如果远程计算机返回Password
telnet.sendTelnetMsg(RequestBody.getPassword()+"\n");//传输用户密码,改写你的密码
Thread.sleep(1000);
if(telnet.findStr("Welcome"))//如果远程计算机返回Welcome字符
{
telnet.sendTelnetMsg(RequestBody.getCommand() + "\n");//发送指令
Thread.sleep(1000);
String msg = telnet.readTelnetMsg();
telnet.close();
return msg;
}
return null;
}
}