java连接telnet进行操作

java连接telnet进行操作
9853人阅读 评论(2) 收藏 举报
本文章已收录于:
分类:
使用java连接telnet进行操作的注意
1.telnet有VT100 VT52 VT220 VTNT ANSI等协议。
我用vt100。
2.vt100控制码(ansi控制码)过滤的问题,可以过滤,也可以在服务设置不要。
不过滤都是一些乱码。是以\033[***一个字母结尾的格式。
3.中文乱码的问题。
new String(old.getBytes("ISO8859-1"),"GBK")。
4.如何判断读取到最后了。
一有readUntil(),二有使用线程。
5.选择telnet的java包问题,包有很多,比如appache(commons-net-3.1.jar), ganymed(ganymed-ssh2-build210.jar),javaexpect(smart-0.1-SNAPSHOT-jar-with-dependencies.jar)

我使用appache。javaexpect有带的vt100控制码过滤,我没有仔细研究。

6.write要flush()才发送。


  1. package securecrt.ssh2;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.InputStream;  
  5. import java.io.PrintStream;  
  6. import java.io.UnsupportedEncodingException;  
  7. import java.net.SocketException;  
  8.   
  9. import org.apache.commons.net.telnet.TelnetClient;  
  10.   
  11. /** 
  12.  * telnet操作类。使用appache的net.Telnet包,对vt100控制代码(即ansi控制码)进行简单过滤。 
  13.  *  
  14.  * @author chruan 
  15.  * @version 1.0 
  16.  */  
  17. public class TelnetHelper {  
  18.     Object lock = new Object();  
  19.     TelnetClient telnet = null;  
  20.     String hostname;  
  21.     int hostport = 23;  
  22.     String user;  
  23.     String password;  
  24.     private InputStream in;  
  25.     private PrintStream out;  
  26.     private static final String ORIG_CODEC = "ISO8859-1";  
  27.     private static final String TRANSLATE_CODEC = "GBK";  
  28.   
  29.     public TelnetHelper(String hostname, int hostport, String user,  
  30.             String password) throws SocketException, IOException {  
  31.         super();  
  32.         this.hostname = hostname;  
  33.         this.hostport = hostport;  
  34.         this.user = user;  
  35.         this.password = password;  
  36.   
  37.         telnet = new TelnetClient("VT100");// VT100 VT52 VT220 VTNT ANSI  
  38.         telnet.connect(hostname, hostport);  
  39.         in = telnet.getInputStream();  
  40.         out = new PrintStream(telnet.getOutputStream());  
  41.   
  42.         readUntil("login: ");  
  43.         write(user);  
  44.         write("\n");  
  45.         readUntil("Password: ");  
  46.         write(password);  
  47.         write("\n");  
  48.     }  
  49.   
  50.     public void doJob() {  
  51.         // restartTerminal();  
  52.         counter();  
  53.     }  
  54.   
  55.     private void restartTerminal() {  
  56.         try {  
  57.             readUntil(">");  
  58.             write("telnet 0.0.7.74\n");  
  59.             readUntil("login: ");  
  60.             write("dd\n"500);  
  61.             readToEnd();  
  62.   
  63.             write("dff\n"200);  
  64.             readToEnd();  
  65.   
  66.         } catch (Exception e) {  
  67.             e.printStackTrace();  
  68.         } finally {  
  69.   
  70.         }  
  71.     }  
  72.   
  73.     private void counter() {  
  74.         try {  
  75.             readUntil(">");  
  76.             write("telnet 4.3.4.4\n");  
  77.             readUntil("login: ");  
  78.             write("dd\n"1000);  
  79.             readToEnd();  
  80.   
  81.             write("\r\n"200);  
  82.             readToEnd();  
  83.   
  84.         } catch (Exception e) {  
  85.             e.printStackTrace();  
  86.         } finally {  
  87.   
  88.         }  
  89.     }  
  90.   
  91.     public void readToEnd() {  
  92.         ReadThread readThread = new ReadThread();  
  93.         readThread.start();  
  94.         try {  
  95.             readThread.join();  
  96.         } catch (Exception e) {  
  97.         }  
  98.         readThread = null;  
  99.     }  
  100.   
  101.     public void readUntil(String str) {  
  102.         char last = str.charAt(str.length() - 1);  
  103.         String[] ss;  
  104.         try {  
  105.             StringBuffer sb = new StringBuffer();  
  106.             char c;  
  107.             int code = -1;  
  108.             boolean ansiControl = false;  
  109.             boolean start = true;  
  110.             while ((code = (in.read())) != -1) {  
  111.                 c = (char) code;  
  112.                 if (c == '\033') {//vt100控制码都是以\033开头的。  
  113.                     ansiControl = true;  
  114.                     int code2 = in.read();  
  115.                     char cc = (char) code2;  
  116.                     if (cc == '[' || cc == '(') {  
  117.                     }  
  118.                 }  
  119.                 if (!ansiControl) {  
  120.                     if (c == '\r') {  
  121.                         String olds = new String(sb.toString().getBytes(  
  122.                                 ORIG_CODEC), TRANSLATE_CODEC);  
  123.                         System.out.println(olds);  
  124.                         if (sb.lastIndexOf(str) != -1) {  
  125.                             break;  
  126.                         }  
  127.                         sb.delete(0, sb.length());  
  128.                     } else if (c == '\n')  
  129.                         ;  
  130.                     else  
  131.                         sb.append(c);  
  132.                     if (sb.lastIndexOf(str) != -1) {  
  133.                         break;  
  134.                     }  
  135.                 }  
  136.   
  137.                 if (ansiControl) {  
  138.                     if (('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z')  
  139.                             || c == '"') {  
  140.                         ansiControl = false;  
  141.                     }  
  142.                 }  
  143.             }  
  144.             System.out.println(new String(sb.toString().getBytes(ORIG_CODEC),  
  145.                     TRANSLATE_CODEC));  
  146.         } catch (Exception e) {  
  147.             e.printStackTrace();  
  148.         }  
  149.     }  
  150.   
  151.     public void write(String s) {  
  152.         try {  
  153.             out.write(s.getBytes());  
  154.             out.flush();  
  155.             System.out.println(s);  
  156.         } catch (Exception e) {  
  157.         }  
  158.     }  
  159.   
  160.     public void write(String s, int sleep) {  
  161.         write(s);  
  162.         try {  
  163.             Thread.sleep(sleep);  
  164.         } catch (Exception e) {  
  165.         }  
  166.     }  
  167.   
  168.     /** 
  169.      * 完成之后必须关闭 
  170.      */  
  171.     public void close() {  
  172.         if (out != null)  
  173.             out.close();  
  174.         if (in != null)  
  175.             try {  
  176.                 in.close();  
  177.             } catch (IOException e1) {  
  178.             }  
  179.         if (telnet != null)  
  180.             try {  
  181.                 telnet.disconnect();  
  182.             } catch (IOException e) {  
  183.             }  
  184.     }  
  185.   
  186.     public static void main(String[] args) {  
  187.         String hostname = "44.55.66.77";  
  188.         int hostport = 23;  
  189.         String user = "user";  
  190.         String password = "password";  
  191.         TelnetHelper helper = null;  
  192.         try {  
  193.             helper = new TelnetHelper(hostname, hostport, user, password);  
  194.             helper.doJob();  
  195.   
  196.         } catch (Exception e) {  
  197.             e.printStackTrace();  
  198.         } finally {  
  199.             if (helper != null)  
  200.                 helper.close();  
  201.         }  
  202.     }  
  203.   
  204.     /** 
  205.      * 读取主线程,负责管理子线程。防止读取时不动了,这时就抛弃读取子线程 
  206.      * @author chruan 
  207.      * 
  208.      */  
  209.     class ReadThread extends Thread {  
  210.         public void run() {  
  211.             synchronized (lock) {//只能一个读取  
  212.                 SubReadThread sub = new SubReadThread();  
  213.                 sub.start();  
  214.                 int last = sub.count;  
  215.                 while (true) {  
  216.                     try {  
  217.                         Thread.sleep(100);  
  218.                     } catch (InterruptedException e) {  
  219.                     }  
  220.                     if (last == sub.count) {  
  221.                         sub.stop();  
  222.                         break;  
  223.                     } else {  
  224.                         last = sub.count;  
  225.                     }  
  226.                 }  
  227.                 String s = sub.sb.toString();  
  228.                 try {  
  229.                     System.out.println(new String(s.getBytes(ORIG_CODEC),  
  230.                             TRANSLATE_CODEC));  
  231.                 } catch (UnsupportedEncodingException e) {  
  232.                     System.out.println(s);  
  233.                 }  
  234.                 sub = null;  
  235.             }  
  236.   
  237. //          System.out.println("===========ReadThread end=============");  
  238.         }  
  239.     }  
  240.   
  241.     /** 
  242.      * 读取子线程,完成实际读取 
  243.      * @author chruan 
  244.      * 
  245.      */  
  246.     class SubReadThread extends Thread {  
  247.         int count = 0;  
  248.         StringBuffer sb = new StringBuffer();  
  249.   
  250.         public void read() {  
  251.             try {  
  252.                 char c;  
  253.                 int code = -1;  
  254.                 boolean ansiControl = false;  
  255.                 boolean start = true;  
  256.                 while ((code = (in.read())) != -1) {  
  257.                     count++;  
  258.                     c = (char) code;  
  259.                     if (c == '\033') {  
  260.                         ansiControl = true;  
  261.                         int code2 = in.read();  
  262.                         char cc = (char) code2;  
  263.                         count++;  
  264.                         if (cc == '[' || cc == '(') {  
  265.                         }  
  266.                     }  
  267.                     if (!ansiControl) {  
  268.                         if (c == '\r') {  
  269.                             String olds = new String(sb.toString().getBytes(  
  270.                                     ORIG_CODEC), TRANSLATE_CODEC);  
  271.                             System.out.println(olds);  
  272.                             sb.delete(0, sb.length());  
  273.                         } else if (c == '\n')  
  274.                             ;  
  275.                         else  
  276.                             sb.append(c);  
  277.                     }  
  278.   
  279.                     if (ansiControl) {  
  280.                         if (('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z')  
  281.                                 || c == '"') {  
  282.                             ansiControl = false;  
  283.                         }  
  284.                     }  
  285.                 }  
  286.             } catch (Exception e) {  
  287.             }  
  288.         }  
  289.   
  290.         public void run() {  
  291.             read();  
  292.         }  
  293.     }  
  294. }  
package securecrt.ssh2;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.net.SocketException;

import org.apache.commons.net.telnet.TelnetClient;

/**
 * telnet操作类。使用appache的net.Telnet包,对vt100控制代码(即ansi控制码)进行简单过滤。
 * 
 * @author chruan
 * @version 1.0
 */
public class TelnetHelper {
	Object lock = new Object();
	TelnetClient telnet = null;
	String hostname;
	int hostport = 23;
	String user;
	String password;
	private InputStream in;
	private PrintStream out;
	private static final String ORIG_CODEC = "ISO8859-1";
	private static final String TRANSLATE_CODEC = "GBK";

	public TelnetHelper(String hostname, int hostport, String user,
			String password) throws SocketException, IOException {
		super();
		this.hostname = hostname;
		this.hostport = hostport;
		this.user = user;
		this.password = password;

		telnet = new TelnetClient("VT100");// VT100 VT52 VT220 VTNT ANSI
		telnet.connect(hostname, hostport);
		in = telnet.getInputStream();
		out = new PrintStream(telnet.getOutputStream());

		readUntil("login: ");
		write(user);
		write("\n");
		readUntil("Password: ");
		write(password);
		write("\n");
	}

	public void doJob() {
		// restartTerminal();
		counter();
	}

	private void restartTerminal() {
		try {
			readUntil(">");
			write("telnet 0.0.7.74\n");
			readUntil("login: ");
			write("dd\n", 500);
			readToEnd();

			write("dff\n", 200);
			readToEnd();

		} catch (Exception e) {
			e.printStackTrace();
		} finally {

		}
	}

	private void counter() {
		try {
			readUntil(">");
			write("telnet 4.3.4.4\n");
			readUntil("login: ");
			write("dd\n", 1000);
			readToEnd();

			write("\r\n", 200);
			readToEnd();

		} catch (Exception e) {
			e.printStackTrace();
		} finally {

		}
	}

	public void readToEnd() {
		ReadThread readThread = new ReadThread();
		readThread.start();
		try {
			readThread.join();
		} catch (Exception e) {
		}
		readThread = null;
	}

	public void readUntil(String str) {
		char last = str.charAt(str.length() - 1);
		String[] ss;
		try {
			StringBuffer sb = new StringBuffer();
			char c;
			int code = -1;
			boolean ansiControl = false;
			boolean start = true;
			while ((code = (in.read())) != -1) {
				c = (char) code;
				if (c == '\033') {//vt100控制码都是以\033开头的。
					ansiControl = true;
					int code2 = in.read();
					char cc = (char) code2;
					if (cc == '[' || cc == '(') {
					}
				}
				if (!ansiControl) {
					if (c == '\r') {
						String olds = new String(sb.toString().getBytes(
								ORIG_CODEC), TRANSLATE_CODEC);
						System.out.println(olds);
						if (sb.lastIndexOf(str) != -1) {
							break;
						}
						sb.delete(0, sb.length());
					} else if (c == '\n')
						;
					else
						sb.append(c);
					if (sb.lastIndexOf(str) != -1) {
						break;
					}
				}

				if (ansiControl) {
					if (('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z')
							|| c == '"') {
						ansiControl = false;
					}
				}
			}
			System.out.println(new String(sb.toString().getBytes(ORIG_CODEC),
					TRANSLATE_CODEC));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void write(String s) {
		try {
			out.write(s.getBytes());
			out.flush();
			System.out.println(s);
		} catch (Exception e) {
		}
	}

	public void write(String s, int sleep) {
		write(s);
		try {
			Thread.sleep(sleep);
		} catch (Exception e) {
		}
	}

	/**
	 * 完成之后必须关闭
	 */
	public void close() {
		if (out != null)
			out.close();
		if (in != null)
			try {
				in.close();
			} catch (IOException e1) {
			}
		if (telnet != null)
			try {
				telnet.disconnect();
			} catch (IOException e) {
			}
	}

	public static void main(String[] args) {
		String hostname = "44.55.66.77";
		int hostport = 23;
		String user = "user";
		String password = "password";
		TelnetHelper helper = null;
		try {
			helper = new TelnetHelper(hostname, hostport, user, password);
			helper.doJob();

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (helper != null)
				helper.close();
		}
	}

	/**
	 * 读取主线程,负责管理子线程。防止读取时不动了,这时就抛弃读取子线程
	 * @author chruan
	 *
	 */
	class ReadThread extends Thread {
		public void run() {
			synchronized (lock) {//只能一个读取
				SubReadThread sub = new SubReadThread();
				sub.start();
				int last = sub.count;
				while (true) {
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
					}
					if (last == sub.count) {
						sub.stop();
						break;
					} else {
						last = sub.count;
					}
				}
				String s = sub.sb.toString();
				try {
					System.out.println(new String(s.getBytes(ORIG_CODEC),
							TRANSLATE_CODEC));
				} catch (UnsupportedEncodingException e) {
					System.out.println(s);
				}
				sub = null;
			}

//			System.out.println("===========ReadThread end=============");
		}
	}

	/**
	 * 读取子线程,完成实际读取
	 * @author chruan
	 *
	 */
	class SubReadThread extends Thread {
		int count = 0;
		StringBuffer sb = new StringBuffer();

		public void read() {
			try {
				char c;
				int code = -1;
				boolean ansiControl = false;
				boolean start = true;
				while ((code = (in.read())) != -1) {
					count++;
					c = (char) code;
					if (c == '\033') {
						ansiControl = true;
						int code2 = in.read();
						char cc = (char) code2;
						count++;
						if (cc == '[' || cc == '(') {
						}
					}
					if (!ansiControl) {
						if (c == '\r') {
							String olds = new String(sb.toString().getBytes(
									ORIG_CODEC), TRANSLATE_CODEC);
							System.out.println(olds);
							sb.delete(0, sb.length());
						} else if (c == '\n')
							;
						else
							sb.append(c);
					}

					if (ansiControl) {
						if (('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z')
								|| c == '"') {
							ansiControl = false;
						}
					}
				}
			} catch (Exception e) {
			}
		}

		public void run() {
			read();
		}
	}
}


0
0
 
 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值