- 爱易网页
-
Linux
- java 远道实现操作Linux
日期:2014-05-16 浏览次数:20655 次
java 远程实现操作Linux
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();
}
}
}
免责声明: 本文仅代表作者个人观点,与爱易网无关。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。