使用java實現telnet-client工具分享_java

來源:互聯網
上載者:User

telnet-client太費盡了,比ssh-client費盡的多,搞了一天,湊合能用,還得改。
org.apache.commons.net.telnet.TelnetClien --使用了apache的commons-net包,commons-net-3.0.1-bin.zip。

複製代碼 代碼如下:

package org.sl.util;
import org.apache.commons.net.telnet.TelnetClient;
import java.io.*;
import java.nio.ByteBuffer;
public class TelnetUtil {
    String charset = null;
    byte[] buff = new byte[2048];
    TelnetClient telnetClient = new TelnetClient();
    BufferedReader telnetReader = null;
    BufferedWriter telnetWirter = null;
    InputStream telnetIn = null;
    OutputStream telnetOut = null;

    public TelnetUtil() {
        telnetClient = new TelnetClient();
    }

    /**
     * 串連至伺服器
     * @param ip
     * @param port
     * @throws UnsupportedEncodingException
     * @throws IOException
     */
    public void connect(String ip, int port) throws UnsupportedEncodingException,IOException {
        telnetClient.connect(ip,port);
        setIOStream();
    }

    /**
     * 串連至伺服器
      * @param ip
     * @throws UnsupportedEncodingException
     * @throws IOException
     */
    public void connect(String ip) throws UnsupportedEncodingException,IOException {
        telnetClient.connect(ip);
        setIOStream();
    }

    void setIOStream() throws UnsupportedEncodingException {
        telnetIn = telnetClient.getInputStream();
        telnetOut = telnetClient.getOutputStream();
        if(null==charset){
            telnetReader = new BufferedReader(new InputStreamReader(telnetIn));
            telnetWirter = new BufferedWriter(new OutputStreamWriter(telnetOut));
        }else{
            telnetReader = new BufferedReader(new InputStreamReader(telnetIn, charset));
            telnetWirter = new BufferedWriter(new OutputStreamWriter(telnetOut, charset));
        }
    }

    /**
     * 登入
     * @param user
     * @param passwd
     * @return 是否登入成功.
     * @throws IOException
     */
    public boolean login(String user,String passwd) throws IOException {
        String read = readString();
        for(int i=0; ; i++){
            if(-1==read.indexOf("login")){
                read = readString();
            }else{
                break;
            }
        }
        writeText(user);

        read = readString();
        for(int i=0; ; i++){
            if(-1==read.indexOf("Password")){
                read = readString();
            }else{
                break;
            }
        }
        writeText(passwd);

        for(;;){
            read = readString();
            //System.out.println("last:"+read);
            if(-1!=read.indexOf("Last")){
                return true;
            }else if(-1!=read.indexOf("incorrect")){
                return false;
            }
        }
    }

    /**
     * 這是一個測試方法,隨便寫。
     * @throws IOException
     */
    public void show() throws IOException {
//        System.out.println(readString());
//        System.out.println(readString());
//        ByteBuffer tmp = ByteBuffer.allocate(1024);
//        byte[] buff = new byte[1024];
//        while(telnetIn.available()>0){
//            int readLen = readBytes(buff,0,1024);
//            tmp.put(buff,0,readLen);
//        }

//        System.out.println(new String(tmp.array()));
        System.out.println("1 "+readString());
        System.out.println("2 "+readString());
        System.out.println("3 "+readString());
        writeText("root");
        System.out.println("4 " + readString());
        writeText("123456");
        System.out.println("5 "+readString());
//        System.out.println("6 "+readString());
//        System.out.println("7 "+readString());

    }

    public int readBytes(byte[] buff, int offset, int len) throws IOException {
        return telnetIn.read(buff,offset,len);
    }

    /**
     * 讀取字串<br/>
     * 相當於readByte()轉為字串
     * @return
     * @throws IOException
     */
    public String readString() throws IOException {
        int readLen = readBytes(this.buff, 0, this.buff.length);
        if(0<readLen)
            return new String(buff,0,readLen).trim();
        else
            return "";
    }

    /**
     * 讀取一行<br/>
     * 如果伺服器與用戶端不是同一種作業系統,可能導致此方法計行失敗。
     * @return
     * @throws IOException
     */
    public String readLine() throws IOException {
        String read = telnetReader.readLine();
        return null==read?"":read.trim();
    }

    public void writeBytes(byte[] buff, int offset, int len) throws IOException {
        telnetOut.write(buff,offset,len);
    }

    /**
     * 向伺服器寫字串
     * @param text
     * @throws IOException
     */
    public void writeText(String text) throws IOException {
        telnetWirter.write(text);
        telnetWirter.write('\r');
        telnetWirter.write('\n');
        telnetWirter.flush();
    }

    /**
     * 執行命令,並返回結果<br/>
     * 相當於: <br>
     * writeText();  <br/>
     * return readString();
     * @param cmd
     * @return
     * @throws IOException
     */
    public String exec(String cmd) throws IOException {
        writeText(cmd);
        return readString();
    }

    String login1(String user,String passwd) throws IOException {
        String read = null;
        readString();
        readString();
        read = readString();

        if(-1!=read.indexOf("login")){
            writeText(user);
        }

        read = readString();
        if(-1!=read.indexOf("Password")){
            writeText(passwd);
        }

        read  = readString();
        read += readString();
        return read;

//        StringBuffer sb = new StringBuffer();
//        while(null!= (read = readString())){
//            sb.append(read);
//        }
//
//        return sb.toString();
    }

    /**
     * 關閉
     */
    public void close(){
        try{
            writeText("exit");
            writeText("exit");
            writeText("exit");
        }catch(Exception ex){
        }

        try {
            if(null!=telnetIn) telnetIn.close();
        } catch (Exception e) {
        }

        try {
            if(null!=telnetOut) telnetOut.close();
        } catch (Exception e) {
        }

        try {
            if(null!=telnetClient)telnetClient.disconnect();
        } catch (Exception e) {
        }
    }

    /**
     * 設定telnet通訊時的字元集<br/>
     * 注:此字元集與伺服器端字元集沒有必然關係<br/>
     * 此方法需在connect()前調用
     * @param charset
     */
    public void setCharset(String charset ){
        this.charset = charset;
    }

    /**
     * 重新設定buff大小,預設為2048位元組.
     * @param size
     */
    public void setBufferSize(int size){
        this.buff = new byte[size];
    }
}

測試類別

複製代碼 代碼如下:

static void t4(){
        TelnetUtil tu = new TelnetUtil();
        try {
            tu.connect("192.168.2.154");
            System.out.println(tu.login("root", "123456"));
            //tu.show();
            //System.out.println(tu.readString());
            //System.out.println(tu.exec("pwd"));

            System.out.println(tu.exec("echo \"123456789\">1.txt"));
            System.out.println(tu.exec("cat 1.txt"));
        } catch (IOException e) {
            e.printStackTrace();
        }

        tu.close();
    }

    static void t1(){
        TelnetUtil tu = new TelnetUtil();
        try {
            tu.connect("192.168.2.154");
            System.out.println(tu.login("sl1", "coffee8215"));
            //tu.show();
            //System.out.println(tu.readString());
            System.out.println(tu.exec("pwd"));

        } catch (IOException e) {
            e.printStackTrace();
        }

        tu.close();
    }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.