首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

java版本telnet客户端代码

2013-04-20 
求一个java版本telnet客户端代码求一个java版本telnet客户端代码[解决办法]一个简单的JAVA Telnet 客户端

求一个java版本telnet客户端代码
求一个java版本telnet客户端代码
[解决办法]
一个简单的JAVA Telnet 客户端实现
 
commons-net-2.0.jar telnet功能的简单使用,
这个包实现了很多基本的基于Intenet协议,下面是 commons 支持的协议:
FTP/FTPS
NNTP
SMTP
POP3
Telnet
TFTP
Finger
Whois
rexec/rcmd/rlogin
Time (rdate) and Daytime
Echo
Discard
NTP/SNTP
下面简单写一个程序做telnet的测试,此程序仅作测试,所以很多写法并不规范。

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import org.apache.commons.net.telnet.TelnetClient;

public class CommonsTelnetTest {
       private final String ip = ""; // 要telnet的IP地址
       private final String port = "23"; //端口号,默认23
       private final String user = "";//用户名
       private final String pwd = ""; //用户密码
       private final String osTag = "$";// 系统标示符号
       private final TelnetClient tc = new TelnetClient(); //新建一个 TelnetClient对象,此对象是 commons-net-2.0.jar包提供

       private InputStream in; // 输入流,接收返回信息
       private PrintStream out; //像 服务器写入 命令
       public void connect() {
              try {
                     tc.connect(ip, Integer.parseInt(port));
                     in = tc.getInputStream();
                     out = new PrintStream(tc.getOutputStream());
              } catch (Exception e) {
                     System.out.println("connect error !");
              }
       }
       public String execute(String command) {
              connect();
              out.println(command);
              out.flush();
              StringBuffer sb = new StringBuffer();
              try {
                     char ch = (char) in.read();
                     while (true) {
                            sb.append(ch);


                            if (ch == osTag.charAt(osTag.length() - 1)) {
                                   if (sb.toString().endsWith(osTag))
                                          return sb.toString();
                            }
                            ch = (char) in.read();
                     }
              } catch (IOException e) {
                     e.printStackTrace();
              }
              return "error! when the program execute";
       }
       public static void main(String [] args){

              System.out.println(new CommonsTelnetTest().execute("ls"));
       }
}


[解决办法]
package com.hwtt.web.jsf.util;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;

import org.apache.commons.net.telnet.TelnetClient;
import org.eclipse.jdt.internal.compiler.ast.ThisReference;

public class Telnet {
   //static final char LF = 10;
   
   static final char LF = 10;
   static final char CR = 13;
   static final char DC1 = 17;
   
 private String host="192.168.4.19";
 private int   port   =   23;
 private   Socket   socket= null;
 
 private  InputStream   is=null;   
 private OutputStream   os=null;   
 private DataInputStream   sin=null;   
 private PrintStream   sout=null;   
 
 private StringBuffer sb =new StringBuffer();
 
 public  Telnet()
 {
  
 }


 public  Telnet(String host,int   port) 
 {
    
      this.host  =host;
      this.port = port;
 }
 public      int   hand(InputStream   is,   OutputStream   os)   throws   IOException   {   
    while(true)   {   
      int   ch   =   is.read();  
     // System.out.println("Svr[ch]:"   +   ch);
      if(ch==82)
      {
       System.out.println(ch);
      }
      if(ch   <   0   
[解决办法]
   ch   !=   255)   
       return   ch;   
      int   cmd   =   is.read();   
      int   opt   =   is.read();   
      //System.out.println("Svr[cmd&opt]:"   +   cmd+" : "+opt); 
      switch(opt)   {   
        case   1: //   echo协商选项,本程序未处理   
        break;   
        case   3: //   supress   go-ahead(抑制向前选项)   
        break;     
        case   24: //   terminal   type(终端类型选项)   
          if(cmd   ==   253)   {   
           os.write(255);   
           os.write(251);   
           os.write(24);   
             
           os.write(255);   
           os.write(250);   
           os.write(24);   
           os.write(0);   
           os.write("dumb".getBytes());   
           os.write(255);   
           os.write(240);   
          }   else   if   (cmd   ==   250)  //子选项开始   


          {   
           ByteArrayOutputStream   baos   =   new   ByteArrayOutputStream();   
           int   svr   =   is.read();   
           while(svr   !=   240)   {   
            baos.write(svr);   
            //System.out.println("Svr[while]:"   +   svr); 
            svr   =   is.read();   
           }   
           //System.out.println("Svr:"   +   baos.toString());   
          }   
          os.flush();
          break;   
        default:   
        if   (cmd   ==   253)   {   
         os.write(255);   
         os.write(252);   
         os.write(opt);   
         os.flush();
         //System.out.println("Svr[default]:"   +   opt);
        }   
      }   
    }   
    }  
 public void pause(int cnt)
 {
  for(int i=0; i< cnt * 1000000; i++)
  {
   
  }
 }
 public void open(String userName,String password) throws IOException
 {
   socket   =   new   Socket(this.host,   this.port); 
        // System.out.println("client   ok");   
   //获得对应socket的输入/输出流   
       is   =   socket.getInputStream();     
       os   =  socket.getOutputStream();     
       hand(is,os);   
          //输入用户名和密码
          send(userName);
          this.pause(1);
       send(password);
       System.out.println("open :------------1-------------- ");
       System.out.println(receive());
       System.out.println("open :------------1-end ------------- ");


          //执行命令
         String   cmdStr   =   "ls -al";       
         send(cmdStr);   //将读取得字符串传给server   
         System.out.println("open :------------2-------------- ");
         System.out.println(receive());
         System.out.println("open :------------2-end ------------- ");

         //执行命令
         cmdStr   =   "ps -ef";       
         send(cmdStr);   //将读取得字符串传给server   
         System.out.println("open :------------3-------------- ");
         System.out.println(receive());
         System.out.println("open :------------3-end ------------- ");

      //退出telnet
         logOut();
 }
 /**
      * Send data to the remote host.
      * @param buf array of bytes to send
      * @see #receive
      */
  public void logOut() throws IOException {
   //linux
//   String cmdStr="logout"+CR+LF;
//        send(cmdStr.getBytes());
   //windows
   String cmdStr="exit";
        send(cmdStr);
    }
   
     public void send(String cmd) throws IOException {
      String cmdStr = cmd+LF+CR;
      
      os.write(cmdStr.getBytes());
      os.flush();
     }
    
     public void send(byte b) throws IOException {
      System.out.println("Connected   to"+socket.getInetAddress()+":"+   socket.getPort());  
      os.write(b);
      os.flush();
     }

 public String receive() throws IOException
 {
  String result="";
  String temp=null;
  this.pause(1);
  for(int i=0; i< 2; i++)
  {
   temp = receiveData();
   String des=new String(temp.getBytes(),"UTF-8");
   result += des; 
  }
  return result;
 }
 public String receiveData() throws IOException
 {
    StringBuffer sb =new StringBuffer();
       BufferedReader   br   =   new   BufferedReader(new   InputStreamReader(is));


    char[]   buf   =   new   char[1024];
    int   read   =   br.read(buf);    
    String temp=null;
    temp = new   String(buf,0,read);
    //System.out.println("receiveData[while] : "+ temp+" :read: "+read);  
       sb.append(temp);
   return sb.toString(); 
 } 
 
 public void close() throws IOException
 {
 
   //关闭连接   
        if( sin != null ) sin.close();   //关闭数据输入流   
        if( sout != null ) sout.close();   //关闭数据输出流   
        if( is != null ) is.close();   //关闭数据输入流   
        if( os != null ) os.close();   //关闭数据输出流 
        if( socket != null ) 
        {
         socket.close();   //关闭socket 
        }
 }

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
//  TelnetClient tc = new TelnetClient();
  Telnet telnet = new Telnet();
  try
  {
   telnet.open("lb","123456");
   //String str = telnet.receiveData();
   //System.out.println("main : "+str);
   telnet.close();
  }
  catch(IOException ie)
  {
   ie.printStackTrace();
   try
   {
    telnet.close();
   }
   catch(IOException iec)
   {
    iec.printStackTrace();
   }
  }
  
 }

}


[解决办法]
import java.net.*;
import java.io.*;

public class TelnetClient {
 String host="162.105.31.222";  //Telnet服务器地址
 int port=23;  //端口号

 public TelnetClient() {
  System.out.println("Host " + host + "; port " + port);
  try {
   Socket socket = new Socket(host, port); //实例化套接字
   new Listener(socket.getInputStream(), System.out).start(); //输出服务器信息到控制台
   new Listener(System.in, socket.getOutputStream()).start();  //输出控制台信息到服务器
  } catch(IOException ex) {
   ex.printStackTrace(); //输出错误信息
   return;
  }
  System.out.println("Connected Success");
 }

 class Listener extends Thread {


  BufferedReader reader;  //输入流
  PrintStream ps;  //输出流

  Listener(InputStream is, OutputStream os) {
   reader = new BufferedReader(new InputStreamReader(is)); //实例化输入流
   ps = new PrintStream(os); //实例化输出流
  }

  public void run() {
   String line;
   try {
    while ((line = reader.readLine()) != null) {  //读取数据
     ps.print(line); //输出数据
     ps.print("\r\n");
     ps.flush();
    }
   } catch(IOException ex) {
    ex.printStackTrace();
   }
  }
 }
 
 public static void main(String[] argv) {
  new TelnetClient();
 }
}

热点排行