176142998

  BlogJava :: 首页 :: 联系 :: 聚合  :: 管理
  116 Posts :: 0 Stories :: 45 Comments :: 0 Trackbacks

commons-net-2.0.jar
log4j-1.2.15.jar


package com;

import java.io.InputStream;
import java.io.PrintStream;

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

public class TelnetHandler {
 private static final Logger logger = Logger.getLogger(TelnetHandler.class);
 private TelnetClient telnet = new TelnetClient("VT220");
 private InputStream in;
 private PrintStream out;
 private String prompt=" ";
 String s;

 public void TelnetCmd(String server, String user, String password) {
  try {
   // Connect to the specified server
   telnet.connect(server, 23);
   logger.info("Login............................");
   // Get input and output stream references
   in = telnet.getInputStream();
   out = new PrintStream(telnet.getOutputStream());
   // Login
   readUntil("login: ");
   write(user);
   readUntil("password: ");
   write(password);
   // Advance to a prompt
   readUntil(prompt);
  } catch (Exception e) {
   e.printStackTrace();
   logger.info("logon failed", e);
  }
 }

 public String readUntil(String pattern) {
  try {
   char lastChar = pattern.charAt(pattern.length() - 1);
   StringBuffer sb = new StringBuffer();
   // boolean found = false;
   char ch = (char) in.read();

   while (true) {
    System.setProperty("GBK", "iso8859-1");
    System.out.print(ch);
    sb.append(ch);
    if (ch == lastChar) {
     if (sb.toString().endsWith(pattern)) {
      // System.out.print( sb.toString());
      return sb.toString();
     }
    }
    ch = (char) in.read();
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
  return null;
 }

 public void write(String value) {
  try {
   out.println(value);
   out.flush();
//   System.out.println(value);
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

 public String sendCmd(String command) {
  try {
   write(command);
   return readUntil(s + 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 {
   logger.info("发送命令开始");
   TelnetHandler telnet1 = new TelnetHandler();
   telnet1.TelnetCmd("127.0.0.1", "administrator", "123456");
   // Exec Cmd
//   telnet1.sendCmd("dir");
   telnet1.sendCmd("cd c:\\test");
   telnet1.disconnect();
//   telnet1.sendCmd("xcopy c:\\httpdownload.txt c:\\test");
   
   logger.info("发送命令结束");
   
   
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
}

posted on 2011-04-12 17:37 飞飞 阅读(831) 评论(0)  编辑  收藏

只有注册用户登录后才能发表评论。


网站导航: