import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.net.SocketException;
import org.apache.commons.net.telnet.TelnetClient;
/**
* commons-net-2.0.jar是工程依赖包
*/
public class NetTelnet {
TelnetClient telnet = new TelnetClient();// 初始化Telnet客户端连接
private InputStream is;
private PrintStream out;
// telnet连接初始化需要的参数
private String ip;// 远端主机IP
private int port;// telnet连接的端口号
private String user;// 用户名
private String password;// 密码
private char promopt = '$';// 命令提示符 普通用户命令以$号结束
public NetTelnet(String ip, int port, String user, String password) {
this.ip = ip;
this.port = port;
this.user = user;
this.password = password;
initLink(ip, port, user, password, promopt);
}
private void initLink(String ip, int port, String user, String password,
char promopt) {
try {
telnet.connect(ip, port);// 连接到远端主机
is = telnet.getInputStream();
out=new PrintStream(telnet.getOutputStream());
// in=new Scanner(is);
// out=new PrintWriter(os,true);
// 根据是否是root用户设置命令结束符号
this.promopt = user.equals("root") ? '#' : '$';
login(user, password);
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// 登陆主机
private void login(String user, String password) {
readUntil("login:");// 得到远端发来的是输入用户名的指令
write(user);// 输入用户名
readUntil("Password:");
write(password);
readUntil(promopt + "");// 注意这种转化类型的用法
}
// 获取远端主机发送来的指令
public String readUntil(String pattern) {
try {
char lastChar = pattern.charAt(pattern.length() - 1);
StringBuffer sb = new StringBuffer();
char read = (char) is.read();
while (true) {
sb.append(read);
if (read == lastChar) {
if (sb.toString().contains(pattern)) {
return sb.toString();
}
}
read = (char) is.read();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
// 用户发送过去的指令或者数据
public void write(String value) {
out.println( value );
out.flush();
}
// 向远程主机发送命令
public String sendCommand(String command) {
write(command);
return readUntil(promopt + "");
}
// 关闭连接
public void disConnect() {
try {
telnet.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
System.out.println("启动Telnet...");
String ip = "192.168.0.2";
int port = 23;
String user = "user";
String password = "passwprd";
NetTelnet telnet = new NetTelnet(ip, port, user, password);
telnet.sendCommand("export LANG=en");
String r1 = telnet.sendCommand("cd /usr/lib");
String r2 = telnet.sendCommand("pwd");
System.out.println("显示结果");
System.out.println(r1);
System.out.println(r2);
telnet.disConnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
java连接linux
最新推荐文章于 2024-03-22 13:58:03 发布