telnet远程登陆程序

 
  

   commons-net
   commons-net
   3.4
 
  
package cn.tisson.ipran.gdcsgcf.driver.client;

import org.apache.commons.net.telnet.TelnetClient;
import org.apache.commons.net.telnet.TelnetOptionHandler;
import org.apache.commons.net.telnet.TerminalTypeOptionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class TelCommandDriver extends CommandDriver {
   protected Logger log = LoggerFactory.getLogger(TelCommandDriver.class);
   protected TelnetClient telnetClient = null;// telnet客户端
   @Override
   public int open(String ip, int port, String loginPrompt, String userName,
               String pwdPrompt, String pwd, String commandPrompt,StringBuffer resultBuf) {
      if(isOpen){
         return 0;
      }
      if (ip == null || ip.equals("") || port < -1) {
         log.error("需要telnet连接的ip 或端口不正确,请校验,ip="+ip+",port="+port);
         return -1;
      }
      try {
         this.ip=ip;
         telnetClient = new TelnetClient();
         TelnetOptionHandler optionhandler = new TerminalTypeOptionHandler(
               "dumb", true, true, true, true);
         telnetClient.addOptionHandler(optionhandler);
         telnetClient.setDefaultTimeout(2000000);
         telnetClient.connect(ip, port);
         telnetClient.setSoTimeout(2000000);
      } catch (Exception e) {
         resultBuf.append(e.getMessage());
         close();
         log.error(ip+" 打开telnet 连接出现异常,连接ip端口为" + ip + ":" + port, e);
         return -2;
      }
      String result=null;
      try {
         isr = new InputStreamReader(telnetClient.getInputStream(),
               charsetName);
         osr = new OutputStreamWriter(telnetClient.getOutputStream(),
               charsetName);
         result = read(loginPrompt, 30000);
         if (result.indexOf(loginPrompt) < 0) {
            close();
            if(result !=null && !"".equals(result)){
               resultBuf.append(ip+" 没有接收到输入用户名的提示符" + loginPrompt + "接收到的是" + result);
            }
            log.error(ip+" 没有接收到输入用户名的提示符" + loginPrompt + "接收到的是" + result);
            return -3;
         }
         write(userName);
         // add  by yw 延长网元响应时间
         result = read(pwdPrompt, 60000);
         if (result.indexOf(pwdPrompt) < 0) {
            close();
            if(result !=null && !"".equals(result)){
               resultBuf.append(ip+" 没有接收到输入密码的提示符" + pwdPrompt + "接收到的是" + result);
            }
            log.error(ip+" 没有接收到输入密码的提示符" + pwdPrompt + "接收到的是" + result);
            return -4;
         }
         write(pwd);
         result = read(commandPrompt, 30000);
         resultBuf.append(result);
         //yw 2018/4/24
         if(this.isAutoAnswer){
            this.write("N");
            result=read(commandPrompt);
            resultBuf.append(result);
         }
//       write("N");
//       result = read(commandPrompt, 30000);
//       resultBuf.append(result);
         if (result.indexOf(commandPrompt) < 0) {
            resultBuf.append(ip+" 没有接收到成功命令的提示符" + commandPrompt);
            log.error(ip+" 没有接收到成功命令的提示符" + commandPrompt + "接收到的是" + result);
            //认证失败
            if(result.contains("Error")||result.contains(loginPrompt)){
               close();
               log.error(ip+" 认证失败接收到的是" + result);
               return -23;
            }
            close();

            return -5;
         }
         this.commandPrompt=result.substring(result.lastIndexOf("\n")+1);
      } catch (Exception e) {
         resultBuf.append(e.getMessage());
         close();
         log.error(ip+" 读取数据出现异常" + ip + ":" + port, e);
         return -6;
      }
      this.isOpen = true;
      return 0;
   }


   public int open(String ip, int port, String loginPrompt, String userName,
               String pwdPrompt, String pwd, String commandPrompt,StringBuffer resultBuf,String noN) {//open过程中不输入“N”,主要因为九博U3设备在en之前不能有错误命令
      if(isOpen){
         return 0;
      }
      if (ip == null || ip.equals("") || port < -1) {
         log.error("需要telnet连接的ip 或端口不正确,请校验,ip="+ip+",port="+port);
         return -1;
      }
      try {
         this.ip=ip;
         telnetClient = new TelnetClient();
         TelnetOptionHandler optionhandler = new TerminalTypeOptionHandler(
               "dumb", true, true, true, true);
         telnetClient.addOptionHandler(optionhandler);
         telnetClient.setDefaultTimeout(2000000);
         telnetClient.connect(ip, port);
         telnetClient.setSoTimeout(2000000);
      } catch (Exception e) {
         resultBuf.append(e.getMessage());
         close();
         log.error(ip+" 打开telnet 连接出现异常,连接ip端口为" + ip + ":" + port, e);
         return -2;
      }
      String result=null;
      try {
         isr = new InputStreamReader(telnetClient.getInputStream(),
               charsetName);
         osr = new OutputStreamWriter(telnetClient.getOutputStream(),
               charsetName);
         result = read(loginPrompt, 30000);

         if (result.indexOf(loginPrompt) < 0) {
            close();
            if(result !=null && !"".equals(result)){
               resultBuf.append(ip+" 没有接收到输入用户名的提示符" + loginPrompt + "接收到的是" + result);
            }
            log.error(ip+" 没有接收到输入用户名的提示符" + loginPrompt + "接收到的是" + result);
            return -3;
         }
         write(userName);
         // add  by yw 延长网元响应时间
         result = read(pwdPrompt, 60000);

         if (result.indexOf(pwdPrompt) < 0) {
            close();
            if(result !=null && !"".equals(result)){
               resultBuf.append(ip+" 没有接收到输入密码的提示符" + pwdPrompt + "接收到的是" + result);
            }
            log.error(ip+" 没有接收到输入密码的提示符" + pwdPrompt + "接收到的是" + result);
            return -4;
         }
         write(pwd);
         result = read(commandPrompt, 30000);
         resultBuf.append(result);
//       write("N");
//       result = read(commandPrompt, 30000);
         resultBuf.append(result);
         if (result.indexOf(commandPrompt) < 0) {
            resultBuf.append(ip+" 没有接收到成功命令的提示符" + commandPrompt);
            log.error(ip+" 没有接收到成功命令的提示符" + commandPrompt + "接收到的是" + result);
            //认证失败
            if(result.contains("Error")||result.contains(loginPrompt)){
               close();
               log.error(ip+" 认证失败接收到的是" + result);
               return -23;
            }
            close();

            return -5;
         }
         this.commandPrompt=result.substring(result.lastIndexOf("\n")+1);
      } catch (Exception e) {
         resultBuf.append(e.getMessage());
         close();
         log.error(ip+" 读取数据出现异常" + ip + ":" + port, e);
         return -6;
      }
      this.isOpen = true;
      return 0;
   }
   @Override
   public void close(){
      super.close();
      try {
         if (telnetClient != null) {
            telnetClient.disconnect();
         }
      } catch (Exception e) {
      }finally {
         telnetClient = null;
      }
   }
   public static void main(String [] args) throws Exception{
      TelCommandDriver d=new TelCommandDriver();
      //int result=d.open("4.108.128.162", 23, ":", "noc189", ":", "1qaz#EDC", ">");
      StringBuffer buf = new StringBuffer();
      //"10.54.208.76", 23, "swgdjwg", "swwg@123", "swcywsup", buf
      int result=d.open("*.*.*.*", 23, ":", "dd@dd", ":", "jmcsg", ">", buf);
      System.out.println("result="+result);
      if(result>=0){
         buf.delete(0, buf.length());
      }
      System.out.println("buf="+buf);
      if(result==0){
         //d.write("display ip interface brief | include GigabitEthernet");
//       d.write("en");
//       String temp=d.read("#");
//       d.write("2@@5SgJ…R");
         String temp1=d.read(">");
         System.out.println(temp1);
         d.write("dis version");
         String temp2=d.read(">");
         System.out.println(temp2);
      }
      d.close();
   }
}

 
  
package cn.tisson.ipran.gdcsgcf.driver.client;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;


public abstract class CommandDriver implements ICommandDriver{
   protected Logger log = LoggerFactory.getLogger(CommandDriver.class);
   protected InputStreamReader isr;// 输入流
   protected OutputStreamWriter osr;// 输出流
   protected boolean isOpen = false;// 是否已经打开连接,防止打开多次
   protected String ip;
   protected String userName;
   protected String pwd;
   protected String commandPrompt;
   protected String loginPrompt;
   protected String pwdPrompt;
   protected int outTime=10000;
   protected String charsetName="iso8859-1";
   protected String neName;
   protected boolean isAutoAnswer = false;

   public boolean isAutoAnswer() {
      return isAutoAnswer;
   }
   @Override
   public abstract int open(String ip, int port, String loginPrompt, String userName,
                      String pwdPrompt, String pwd, String commandPrompt,StringBuffer resultBuf);
   @Override
   public void close() {
      this.isOpen = false;
      try {
         if (isr != null) {
            isr.close();
         }
      } catch (IOException e) {
         log.error(this.ip + "closed inputStreamRead failed", e);
      } finally {
         isr = null;
      }
      try {
         if (osr != null) {
            osr.close();
         }

      } catch (IOException e) {
         log.error(this.ip + "closed outputStramRead failed", e);
      } finally {
         osr = null;
      }
   }
   @Override
   public void write(String command) throws Exception {
      log.debug(ip+" 发送的命令为"+command);
      clearReadBuffer();
      osr.write(command+ getTerminalSendPostfix());
      osr.flush();
   }

   @Override
   public void write(String command,String terminalSendPostfix) throws Exception {
      log.debug(ip+" 发送的命令为"+command);
      clearReadBuffer();
      osr.write(command+ terminalSendPostfix);
      osr.flush();
   }

   @Override
   public String read() throws Exception {
      return this.read(new StringResponseEndChecker() {

         @Override
         public boolean isResponseEnd(StringBuffer data) {
            if (data!=null&&data.toString().trim().endsWith(commandPrompt)) {
               return true;
            }
            return false;
         }
      }, this.outTime);
   }

   @Override
   public String read(String terminator) throws Exception {
      return this.read(terminator, this.outTime);
   }
   @Override
   public String read(final String terminator,int timeout) throws Exception {
      return this.read(new StringResponseEndChecker() {

         @Override
         public boolean isResponseEnd(StringBuffer data) {
            if (data!=null&&data.toString().trim().endsWith(terminator)) {
               return true;
            }else if(data!=null&&data.toString().trim().endsWith("[Y/N]:")){
               isAutoAnswer=true;
               return true;
            }
            return false;
         }
      }, timeout);
   }
   public boolean isOpen(){
      return this.isOpen;
   }
   @Override
   public void setCharsetName(String charsetName) {
      if(charsetName!=null)
         this.charsetName=charsetName;
   }
   @Override
   public String getUsername() {

      return this.userName;
   }

   @Override
   public String getPassword() {

      return this.pwd;
   }

   @Override
   public String getNeName() {

      return this.neName;
   }
   /**
    * 清空接受
    */
   private void clearReadBuffer() {
      BufferedReader br = null;
      try {
         if (isr!=null) {
            br = new BufferedReader(isr);
            while (br.ready()) {
               br.read();
            }
         }
      } catch (Exception e) {
         log.error("清空read buffer 出现异常", e);
      }
   }
   /**
    * 命令发送结尾符
    * @return
    */
   protected String getTerminalSendPostfix() {
      return "\r\n";
   }
   @Override
   public String read(StringResponseEndChecker checker, long timeout) throws IOException{
      long time = System.currentTimeMillis() + timeout;
      StringBuffer sb = new StringBuffer();
      BufferedReader br = null;
      boolean readed = false;
      boolean isClose=true;//用来判断网络是否正常 true不正常 false正常
      br = new BufferedReader(isr);
      while (System.currentTimeMillis() < time) {
         try {
            if (br.ready()) {
               int brchar = br.read();
               if((32<=brchar&&brchar<=127)||brchar==10||brchar==13) {
                  sb.append((char) brchar);
               }
               readed = true;
               isClose=false;
            } else {
               if ((checker != null) && (readed == true)) {
                  readed = false;
                  if (checker.isResponseEnd(sb))
                     break;
               }
               Thread.sleep(150);
            }
         } catch (InterruptedException e) {
            log.error("读取数据出现异常",e);
         }
      }
      if(isClose&&sb.length()==0){
         this.isOpen=false;
         throw new IOException("网络已经中断.....");
      }
      String temp=sb.toString();
//    temp=temp.substring(temp.indexOf("\n")+1);//删除命令回显
      log.debug(ip+" 接受到的数据为"+temp);
      return temp;
   }
   @Override
   public void setOutTime(int outTime) {
      if(outTime>5000)
         this.outTime = outTime;
   }
   @Override
   public int getOutTime() {
      return outTime;
   }

}
 
  
package cn.tisson.ipran.gdcsgcf.driver.client;

public interface ICommandDriver {
   public boolean isAutoAnswer();
   /**
    * 打开连接
    * @param ip telnet ip地址 如127.0.0.1
    * @param port telnet 端口号 如23
    * @param loginPrompt 用户名输入提示符 如userName:
    * @param userName 用户名 如who
    * @param pwdPrompt 输入密码提示符 如Password:
    * @param pwd 密码 如who
    * @param commandPrompt 登陆成功提示符 如>
    * @return 0成功,-1数据可是不对 -2没有接到输入用户名提示符 -3没有接收到密码提示符 -4没有接到登陆成功提示符 -5出现异常
    */
   public abstract int open(String ip, int port, String loginPrompt,String userName, String pwdPrompt, String pwd,    String commandPrompt,StringBuffer resultBuf);
   /**
    * 关闭连接
    */
   public void close();
   /**
    * 获取登录用户名
    * @return
    */
   public String getUsername();
   /**
    * 获取登录密码
    * @return
    */
   public String getPassword();
   /**
    * 获取网元名称
    * @return
    */
   public String getNeName();
   /**
    * 发送命令
    * @param command
    * @throws Exception
    */
   public void write(String command) throws Exception;
   /**
    * 发送命令
    * @param command
    * @param  terminalSendPostfix \r\n \r
    * @throws Exception
    */
   public void write(String command,String terminalSendPostfix) throws Exception;
   /**
    * 接受命令结果
    * @return
    * @throws Exception
    */
   public String read() throws Exception;
   /**
    * 接受命令结果直到结束
    * @param terminator
    * @return
    * @throws Exception
    */
   public String read(String terminator)throws Exception;
   /**
    * 设置字符集
    * @param charsetName
    */
   public void setCharsetName(String charsetName);
   /**
    * @param terminator
    * @param timeout
    * @return
    * @throws Exception
    */
   String read(String terminator, int timeout) throws Exception;
   /**
    * 返回连接状态  主要是主动关闭
    */
   public boolean isOpen();
   /**
    * 设置默认超时时间单位毫秒
    * @param outTime
    */
   public void setOutTime(int outTime);
   public int getOutTime();
   String read(StringResponseEndChecker checker, long timeout) throws Exception;
}

你可能感兴趣的:(系统命令)