远程利用telnet执行DOS命令

我使用的环境是  memcached 安装在winodws下  而应用安装在Linux.故使用Telnet远程启动memcached.
不说了,直接贴代码.
package com.gdcn.core.telnet;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.SocketException;
import java.util.StringTokenizer;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.net.telnet.EchoOptionHandler;
import org.apache.commons.net.telnet.InvalidTelnetOptionException;
import org.apache.commons.net.telnet.SimpleOptionHandler;
import org.apache.commons.net.telnet.SuppressGAOptionHandler;
import org.apache.commons.net.telnet.TelnetClient;
import org.apache.commons.net.telnet.TelnetNotificationHandler;
import org.apache.commons.net.telnet.TerminalTypeOptionHandler;
import org.apache.log4j.Logger;
/**
 * telnet远程工具类
 * @author [email protected]
 * @date 2014-1-8
 */
public class TelnetUtils implements TelnetNotificationHandler{
 static TelnetClient tc = null;
 static Logger logger = Logger.getLogger(TelnetUtils.class);
 private static String msg;
 
 /**
  * 回调函数
  */
 public void receivedNegotiation(int negotiation_code, int option_code) {
  String command = null;
  if (negotiation_code == TelnetNotificationHandler.RECEIVED_DO) {
   command = "DO";
  } else if (negotiation_code == TelnetNotificationHandler.RECEIVED_DONT) {
   command = "DONT";
  } else if (negotiation_code == TelnetNotificationHandler.RECEIVED_WILL) {
   command = "WILL";
  } else if (negotiation_code == TelnetNotificationHandler.RECEIVED_WONT) {
   command = "WONT";
  }
  logger.info("Received " + command + " for option code " + option_code);
 }
 
 /**
  * 
  * @param remoteip  远程IP地址
  * @param termtype  远程终端系统类型 如果是windows 则传:VT220,如果是linux、unix则传:VT100
  * @param serviceName 远程服务器名称
  * @param servicePwd  远程服务器密码
  * @param remoteport  远程服务器的端口
  * @param commands    需要远程服务器执行的命令
  * @author [email protected]
  * @date 2014-1-7
  */
 public static boolean telnet(String remoteip,String termtype,String serviceName,String servicePwd,int remoteport,String[] commands) {
  boolean flag = false;
  //把用户名和密码 和命令整到一个数组里面
  String[] copyCommads = new String[commands.length + 2];
  copyCommads[0] = serviceName + "\n";
  copyCommads[1] = servicePwd  + "\n";
  for (int i = 0; i < commands.length; i++) {
   copyCommads[i+2] = commands[i]  + "\n";
  }
  
  //打印日志到spy.log文件中
  FileOutputStream fout = null;
  try {
   fout = new FileOutputStream("spy.log", true);
  } catch (IOException e) {
   logger.error("Exception while opening the spy file: " + e.getMessage());
   flag = false;
  }
  tc = new TelnetClient();
  TerminalTypeOptionHandler ttopt = new TerminalTypeOptionHandler(termtype, false, false, true, false);
  EchoOptionHandler echoopt = new EchoOptionHandler(true, false, true, false);
  SuppressGAOptionHandler gaopt = new SuppressGAOptionHandler(true, true, true, true);
  
  try {
   tc.addOptionHandler(ttopt);
   tc.addOptionHandler(echoopt);
   tc.addOptionHandler(gaopt);
  } catch (InvalidTelnetOptionException e) {
   logger.error("Error registering option handlers: " + e.getMessage());
   flag = false;
  }
  try {
   //start 连接
   logger.info("start connection");
   tc.setReaderThread(true);
   tc.connect(remoteip, remoteport);
   tc.setTcpNoDelay(true);
   tc.registerNotifHandler(new TelnetUtils());
   OutputStream outstr = new PrintStream(tc.getOutputStream());
   new Thread(){
    public void run(){
     readServiceReturnInfo();
    }
   }.start();
   
   msg = "";
   try{
    for(String command:copyCommads){
     int i=0;
     Thread.sleep(3000);
     do{
      Thread.sleep(1000);
      i++;
     }while(StringUtils.isBlank(msg) && i<30);
     if(StringUtils.isBlank(msg) && i>=30){
      logger.info("command wait for execute");
      tc.disconnect();
      return false;
     }
     writeCommand(command, fout, outstr);
     msg = "";
    }
    Thread.sleep(3000);
   }catch(Exception e){
    logger.error("error:",e);
    flag = false;
   }
   logger.info("执行完成,退出telnet");
   
   if(tc!=null){
      try {
     tc.disconnect();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
   
   flag = true;
  } catch (SocketException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }finally{
   
  }
  return flag;
 }
 
 
 /**
  * 发送命令到telnet客户端
  * @param command
  * @param fout
  * @param outstr
  * @return
  * @author [email protected]
  * @date 2014-1-8
  */
 private static String writeCommand(String command,FileOutputStream fout,OutputStream outstr){
  if (command.startsWith("AYT")) {
   try {
    logger.info("Sending AYT");
    logger.info("AYT response:" + tc.sendAYT(5000));
   } catch (IOException e) {
    logger.error("Exception waiting AYT response: " + e.getMessage());
   }catch (IllegalArgumentException e) {
    e.printStackTrace();
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  } else if (command.startsWith("OPT")) {
   logger.info("Status of options:");
   for (int ii = 0; ii < 25; ii++)
    logger.info("Local Option " + ii + ":" + tc.getLocalOptionState(ii) + " Remote Option " + ii + ":" + tc.getRemoteOptionState(ii));
  } else if (command.startsWith("REGISTER")) {
   StringTokenizer st = new StringTokenizer(command);
   try {
    st.nextToken();
    int opcode = Integer.parseInt(st.nextToken());
    boolean initlocal = Boolean.parseBoolean(st.nextToken());
    boolean initremote = Boolean.parseBoolean(st.nextToken());
    boolean acceptlocal = Boolean.parseBoolean(st.nextToken());
    boolean acceptremote = Boolean.parseBoolean(st.nextToken());
    SimpleOptionHandler opthand = new SimpleOptionHandler(opcode, initlocal, initremote, acceptlocal, acceptremote);
    tc.addOptionHandler(opthand);
   } catch (Exception e) {
    if (e instanceof InvalidTelnetOptionException) {
     logger.error("Error registering option: " + e.getMessage());
    } else {
     logger.error("Invalid REGISTER command.");
     logger.error("Use REGISTER optcode initlocal initremote acceptlocal acceptremote");
     logger.error("(optcode is an integer.)");
     logger.error("(initlocal, initremote, acceptlocal, acceptremote are boolean)");
    }
   }
  } else if (command.startsWith("UNREGISTER")) {
   StringTokenizer st = new StringTokenizer(command);
   try {
    st.nextToken();
    int opcode = (new Integer(st.nextToken())).intValue();
    tc.deleteOptionHandler(opcode);
   } catch (Exception e) {
    if (e instanceof InvalidTelnetOptionException) {
     logger.error("Error unregistering option: " + e.getMessage());
    } else {
     logger.error("Invalid UNREGISTER command.");
     logger.error("Use UNREGISTER optcode");
     logger.error("(optcode is an integer)");
    }
   }
  } else if (command.startsWith("SPY")) {
   tc.registerSpyStream(fout);
  } else if (command.startsWith("UNSPY")) {
   tc.stopSpyStream();
  } else {
   try {
    ((PrintStream) outstr).print(command);
    outstr.flush();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
  return null;
 }
 
 /**
  * 获取终端服务器返回的信息
  * 
  * @author [email protected]
  * @date 2014-1-7
  */
 private static void readServiceReturnInfo() {
  msg="";
  InputStream instr=tc.getInputStream();
  try {
   byte[] buff = new byte[1024];
   int ret_read = 0;
   do {
    ret_read = instr.read(buff);
    String returnMsg="";
    if (ret_read > 0) {
     returnMsg += new String(buff,0, ret_read);
    }
    logger.info(returnMsg);
    msg = returnMsg;
   } while (ret_read >= 0);
  } catch (IOException e) {
   logger.error("Exception while reading socket:" + e.getMessage());
  }
  //主线程已经关闭了Telnet客户端了 子线程不需要在关闭线程
  /*try {
   tc.disconnect();
  } catch (IOException e) {
   logger.error("Exception while closing telnet");
  }*/
 }
 
 /**
  * 程序的入口
  * @param args
  * @throws Exception
  * @author [email protected]
  * @date 2014-1-7
  */
 public static void main(String[] args) throws Exception {
  String[] commands={"sc stop \"Memcached Server\"","sc stop \"Memcached Server1\"","sc stop \"Memcached Server2\"","net stop mysql","ipconfig\n","dir"};
  
 }


}
中间导入的apache的commons-net-2.0.jar的包.

你可能感兴趣的:(Java)