日期:2014-05-19 浏览次数:20851 次
import org.apache.commons.net.telnet.*; import java.io.*; import java.net.SocketException; import java.util.StringTokenizer; public class TmhTelnet2 implements Runnable, TelnetNotificationHandler { private static TelnetClient tc = null; private InputStream in; private PrintStream out; public static void main(String args[]){ Thread t = new Thread(new TmhTelnet2("192.168.0.101",23,"admin","admin")); t.start(); } public TmhTelnet2(String host, int port,String username,String password) { if(intconnect(host,port)){ write(username); write(password); writescript("d:\\command.txt"); } } private void writescript(String filename) { try { if(new File(filename).exists()){ FileReader f = new FileReader(filename); BufferedReader reader = new BufferedReader(f); String command = ""; while(command !=null){ command = reader.readLine(); write(command); } } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void write(String command) { try{ System.out.println("command:>>>>>>>>>"+command); out.println(command); out.flush(); }catch(Exception e){ e.printStackTrace(); } } private boolean intconnect(String host, int port) { try { tc = new TelnetClient(); TerminalTypeOptionHandler ttopt = new TerminalTypeOptionHandler( "VT100", false, false, true, false); EchoOptionHandler echoopt = new EchoOptionHandler(true, false, true, false); SuppressGAOptionHandler gaopt = new SuppressGAOptionHandler(true, true, true, true); tc.addOptionHandler(ttopt); tc.addOptionHandler(echoopt); tc.addOptionHandler(gaopt); tc.connect(host, port); in = tc.getInputStream(); out = new PrintStream(tc.getOutputStream()); return true; } catch (Exception e) { e.printStackTrace(); try { tc.disconnect(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } return false; } } 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