基於socket用java實現telnet功能

shallowlearning發表於2015-08-19

一、目的

導師安排了個任務:linux下利用java寫一個程式,使其完成以下功能:使用者輸入兩個引數,一個是遠端伺服器的站點地址例如route-server.belwue.de,二是需要traceroute的ip地址(例如1.1.1.1)。

接著,該程式能telnet到route-server.belwue.de上,然後執行traceroute 1.1.1.1命令,程式將執行該命令獲得的結果返回。需要注意的是telnet到伺服器後,可能需要賬號和密碼(也可能不用),然而賬號密碼已經在登入後的返回結果裡有提示了,比如“login with User and password User”,需要將其解析出來並輸入。

二、程式碼

package test;

//import java.io.InputStream;
//import java.io.PrintStream;
import java.util.*;
import java.io.*;
import org.apache.commons.net.telnet.TelnetClient;

/**
 * 利用apache net 開源包,使用telnet方式獲取AIX主機資訊
 * @version 1.2
 */
public class NetTelnet {

 // Telnet物件
 private TelnetClient telnet = new TelnetClient();

 private InputStream in;

 private PrintStream out;



 // 提示符。具體請telnet到AIX主機檢視
 private char prompt = '#';

 // telnet埠
 private String port;

 // 使用者
 private String user;

 // 密碼
 private String password;

 // IP地址
 private String ip;

 public NetTelnet(String Server) {

  try {
   // AIX主機IP
   //this.ip = "route-server.ip.att.net";
   this.ip=Server;
   this.password = "rviews";
   this.user = "rviews";
   this.port = "23";
   telnet.connect(ip, Integer.parseInt(port));
   //System.out.println("開始獲取輸入流...");
   in = telnet.getInputStream();
   out = new PrintStream(telnet.getOutputStream());
   // 登入

   //以下程式碼片是用於判別出各種不同伺服器的返回資訊
   //因為伺服器數量不多,所以直接採取有限狀態判斷的辦法
   if (Server.equals("route-server.ip.att.net"))
   {
       readUntil("login:");
       write("rviews");
       readUntil("Password:");
       write("rviews");
   }   
   else if (Server.equals("route-server.twtelecom.net"))
   {
       readUntil("login:");
       write("rviews");
       readUntil("Password:");
       write("rviews123");
   }   
   else if (Server.equals("public-route-server.is.co.za"))
   {
       readUntil("Username:");
       write("rviews");
       readUntil("Password:");
       write("rviews");
   }
   else if (Server.equals("tpr-route-server.saix.net"))
   {
       readUntil("Username:");
       write("saix");
       readUntil("Password:");
       write("saix");
   }

   else if (Server.equals("route-server.as6667.net"))
   {
       readUntil("login:");
       write("rviews");
       readUntil("Password:");
       write("Rviews");
   }   
   else if (Server.equals("route-server.newyork.ny.ibone.comcast.net"))
   {
       readUntil("Username:");
       write("rviews");
   }   
   else if (Server.equals("route-server.host.net"))
   {
       readUntil("Password:");
       write("routes");
   }
   else if (Server.equals("route-server.east.allstream.com"))
   {
       readUntil("Username:");
       write("rserv");
   }
   else if (Server.equals("route-server.west.allstream.com"))
   {
       readUntil("Username:");
       write("rserv");
   }
   else if (Server.equals("route-server.nevadanap.com"))
   {
       readUntil("Password:");
       write("rviews");
   }
   else if (Server.equals("route-views.oregon-ix.net"))
   {
       readUntil("Username:");
       write("rviews");
   }

   //readUntil(prompt + " ");
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

 /**
  * 讀取分析結果
  * 
  * @param pattern
  * @return
  */
 public String readUntil(String pattern) {
  try {
   char lastChar = pattern.charAt(pattern.length() - 1);//最後一個字元
   StringBuffer sb = new StringBuffer();
   //long startMili=System.currentTimeMillis();
   //long endMili=System.currentTimeMillis();
   char ch = (char) in.read();
   while (true) {
    sb.append(ch);//若未到最後一個字元則繼續對比下一個字元,並把當前字元儲存進sb中
    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 endUntil(String pattern1,String pattern2) {
      try {
       char lastChar = pattern1.charAt(pattern1.length() - 1);//最後一個字元
       StringBuffer sb = new StringBuffer();
       //long startMili=System.currentTimeMillis();
       //long endMili=System.currentTimeMillis();
       char ch = (char) in.read();
       while (true) {
        sb.append(ch);//若未到最後一個字元則繼續對比下一個字元,並把當前字元儲存進sb中
        if (ch == lastChar) {
         if (sb.toString().endsWith(pattern1)) {
          return sb.toString();
         }       
         if (sb.toString().endsWith(pattern2)) {
              return sb.toString();
         }
        }
        ch = (char) in.read();
       }
      } catch (Exception e) {
       e.printStackTrace();
      }
      return null;
}

 public String sendCommand(String command, String ipAddress) {
  try {
   write(command+ipAddress);
   System.out.println(command+ipAddress);
   //return readUntil(prompt + " ");
   readUntil(command+ipAddress);
   //System.out.println("check1");
   //readUntil("jym");
   //System.out.println("check2");
   return endUntil("*  *  *","* * *");
  } catch (Exception e) {
   e.printStackTrace();
  }
  return null;
 }

 /**
  * 關閉連線
  * 
  */
 public void disconnect() {
  try {
   telnet.disconnect();
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

 public static void main(String[] arg) {
  try {
   //System.out.println("開始執行telnet......");
   String Server=arg[0];//"route-server.belwue.de";
   String ipAddress=arg[1];//"1.1.1.1";
   NetTelnet telnet = new NetTelnet(Server);
   String result = telnet.sendCommand("traceroute ",ipAddress);
   //System.out.println("顯示結果");
   System.out.println(result);
   // 最後一定要關閉
   telnet.disconnect();
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
}

程式碼參考連結:
http://zhidao.baidu.com/link?url=2rxqQx9ZTwt9OpL_FrC9UIdA1aXV4qWkV2SpfTmpnbvrmOChXo9daDMKaKddfJ2DxYOMbdClakNwipUpZfQbCpxqTP3P_O-1f0qctVqEaNu

相關文章