测试环境为win7 64位

import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.net.telnet.EchoOptionHandler;
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;
public class TelnetUtil implements Runnable, TelnetNotificationHandler {
    private TelnetClient tc = null;
    private String remoteip;
    private int remoteport;
    private boolean isOver=false;
    private StringBuffer responseStr= new StringBuffer();
    
    
    public TelnetUtil (String ip){
        this(ip, 23,null);
    }
    public TelnetUtil (String ip,int port){
        this(ip, port,null);
    }
    public TelnetUtil (String ip,String spyFile){
        this(ip, 23,spyFile);
    }
    /**
     * 最终构造方法
     * @param ip
     * @param port
     * @param spyFile
     */
    public TelnetUtil (String ip,int port,String spyFile){
        remoteip=  ip;
        remoteport=port;
        
        initClient(spyFile);
    }

    private void initClient(String spyFile) {
        

        tc = new TelnetClient();

        TerminalTypeOptionHandler ttopt = new TerminalTypeOptionHandler(
                "VT220", 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);
            
            if(null != spyFile && !"".equals(spyFile)){
                FileOutputStream fout = null;
                try {
                    fout = new FileOutputStream("spy.log", true);
                    tc.registerSpyStream(fout);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public String connect(long waitTime) throws Exception {
        try {
            tc.connect(remoteip, remoteport);

            Thread reader = new Thread(this);
            tc.registerNotifHandler(this);
            reader.start();
            return getResponse( waitTime);
        } catch (Exception e) {    
            e.printStackTrace();
            throw new Exception("telnet 连接失败", e);
        }
    }

    public void disConnect() {
        try {
            if(tc != null&& tc.isConnected())
            tc.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    /**
     * 发送命令,返回结果请调用 getResponse(long waitTime)
     * @param command
     * @throws Exception
     */
    public void sendCommand(String command) throws Exception {
        
        try {
            responseStr.delete(0, responseStr.capacity());
            DataOutputStream dataOS = new DataOutputStream(tc.getOutputStream());  
            OutputStreamWriter outSW = new OutputStreamWriter(dataOS, "GB2312");  
            BufferedWriter bw = new BufferedWriter(outSW);  
            bw.write(command);
            bw.write(13);
            bw.write(10);
            bw.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    /**
     * 发送命令
     * @param command 命令
     * @param waitTime 获取返回结果时等待时间,在等待的时间内若返回的结果不是想要的结果,可以调用 getResponse(long waitTime)继续获取
     * @return 执行结果
     * @throws Exception
     */
    public String sendCommand(String command,int waitTime) throws Exception {
        
        
        try {
            responseStr.delete(0, responseStr.capacity());
            DataOutputStream dataOS = new DataOutputStream(tc.getOutputStream());  
            OutputStreamWriter outSW = new OutputStreamWriter(dataOS, "GB2312");  
            BufferedWriter bw = new BufferedWriter(outSW);  
            bw.write(command);
            bw.write(13);
            bw.write(10);
            bw.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return getResponse(waitTime);
        
    }

    
    @Override
    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";
        }
    }

    /***
     * Reader thread. Reads lines from the TelnetClient and echoes them on the
     * screen.
     ***/
    //@Override
    public void run() {
        InputStream instr = tc.getInputStream();
        try {
            
            byte[] buff = new byte[1024];
            int ret_read = 0;        
            do {
                ret_read = instr.read(buff);
                if (ret_read > 0) {
                    responseStr.append(new String(buff, 0, ret_read,"iso-8859-1"));
                }
            } while (ret_read >= 0);
        } catch (Exception e) {
            e.getStackTrace();
        }
    }
    /**
     * 获取命令返回去
     * @param waitTime 等待时间
     * @return
     * @throws UnsupportedEncodingException
     */
    public String getResponse(long waitTime) throws UnsupportedEncodingException
    {
        try {
            Thread.sleep(waitTime);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //return responseStr.toString();
        return new String(responseStr.toString().getBytes("iso-8859-1"),"GB2312");
    }
    
    public static void main(String[] args) throws Exception {
        TelnetUtil util = new TelnetUtil("192.168.1.17");        
        String welcome=util.connect(2000);
        if(welcome.contains("Microsoft")){
            System.out.println("widows opreation");
        }else{
            System.out.println("linux opreation");
        }
        System.out.println(welcome);
        
        
        System.out.println(util.sendCommand("administrator",1000));
        
        System.out.println(util.sendCommand("123456",1000));
        System.out.println(util.sendCommand("d:",1000));
        System.out.println(util.sendCommand("dir",1000));
        System.out.println(util.sendCommand("cd D:/Program Files/ffmpeg/bin",2000));
        System.out.println(util.pattInfo(util.sendCommand("ffmpeg -i e:/贵F1834_1.mp4",1000)));
        String cmd="ffmpeg -i e:/贵F1834_1.mp4 -vf \"drawtext=fontfile=simsun.ttc: text='2016年10月29日' : timecode='09\\:57\\:00\\:00': r=30:x=10: y=10:fontcolor=red:fontsize=24: box=1: boxcolor=0x000000ff@0\" -b 12500k -metadata title=\"my title\" -vcodec libx264  -acodec copy -y d:/贵out.mp4";
        System.out.println(util.sendCommand(cmd,9000));
        util.disConnect();
    }
    public String pattInfo(String info) {
        String regexDuration = "Duration: (.*?), start: (.*?), bitrate: (\\d*) kb\\/s";
        Pattern pattern = Pattern.compile(regexDuration);
        Matcher m = pattern.matcher(info);
        if (m.find()) {
            return m.group(3)+"k";
        }else{
            return "3000k";
        }
    }
    
}


注意:本文归作者所有,未经作者允许,不得转载