java通过telnet执行命令操作远程机器 之方式一

文章转自:http://blog.csdn.net/naughty610/article/details/5723209

经自己测试成功:本机win8   远程机器centos6.3

一.代码

package test1;
/**  * commons-net-3.3.jar是工程依赖包   */
import java.io.InputStream;
import java.io.PrintStream;
import org.apache.commons.net.telnet.TelnetClient;
public class NetTelnet {
	private TelnetClient telnet = new TelnetClient("VT52");
	private InputStream in;
	private PrintStream out;
	private char prompt = '$';

	// 普通用户结束
	public NetTelnet(String ip, int port, String user, String password) {
		try {
			telnet.connect(ip, port);
			in = telnet.getInputStream();
			out = new PrintStream(telnet.getOutputStream());
			// 根据root用户设置结束符
			this.prompt = user.equals("root") ? '#' : '$';
			login(user, password);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/** * 登录 * * @param user * @param password */
	public void login(String user, String password) {
		readUntil("login:");
		write(user);
		readUntil("Password:");
		write(password);
		readUntil(prompt + " ");
	}

	/** * 读取分析结果 * * @param pattern * @return */
	public String readUntil(String pattern) {
		try {
			char lastChar = pattern.charAt(pattern.length() - 1);
			StringBuffer sb = new StringBuffer();
			char ch = (char) in.read();
			while (true) {
				System.out.print(ch);
				sb.append(ch);
				if (ch == lastChar) {
					if (sb.toString().endsWith(pattern)) {
						return sb.toString();
					}
				}
				ch = (char) in.read();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/** * 写操作 * * @param value */
	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 {
			telnet.disconnect();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		try {
			String ip = "192.168.0.11";
			int port = 23;
			String user = "telnet";//远程机器为centos6.3   不能是root用户。useradd命令添加的用户
			String password = "telnet";
			NetTelnet telnet = new NetTelnet(ip, port, user, password);
			telnet.sendCommand("cd /home/telnet/");
			telnet.sendCommand("pwd");
			telnet.sendCommand("ls");
			telnet.disconnect();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
二.myeclipse控制台打印结果

CentOS release 6.3 (Final)
Kernel 2.6.32-279.el6.x86_64 on an x86_64
login: Password: 
Last login: Sat Mar 14 22:49:54 from 192.168.100.211
[telnet@inmsapp1 ~]$ cd /home/telnet/
[telnet@inmsapp1 ~]$ pwd
/home/telnet
[telnet@inmsapp1 ~]$ ls
Desktop  test  testTelnet
[telnet@inmsapp1 ~]$ 

用本机win8  cmd  直接用telnet命令访问远程机器截图

java通过telnet执行命令操作远程机器 之方式一_第1张图片




你可能感兴趣的:(Telnet)