保存telnet的输出

时间:2013-09-11 05:53:09

标签: java string telnet

我已经用java创建了telnet,但我不知道如何将输出保存到文件中.. 可以帮我?? 这是我的代码......

这是为了连接目标

     public class telnetsample
     {
     private static TelnetClient telnet = new TelnetClient();
     private InputStream in;
     private PrintStream out;
     private char prompt = '$';

     public telnetsample( String server, String username, String password , String command) {
     try {
 // Connect to the specified server
 telnet.connect( server, 23 );

 // Get input and output stream references
 in = telnet.getInputStream();
 out = new PrintStream( telnet.getOutputStream() );

 // Log the user on
 readUntil( "Username: " );
 write( username );
 readUntil( "Password: " );
 write( password );
     readUntil ("hostname");
     write (command);


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

这是为了读取终端上的命令

    public String readUntil( String pattern ) {
  try {
 char lastChar = pattern.charAt( pattern.length() - 1 );
 StringBuffer sb = new StringBuffer();
 boolean found = false;
 char ch = ( char )in.read();
 while( true ) {
  System.out.print( ch );
  sb.append( ch );
  if( ch == lastChar ) {
    if( sb.toString().endsWith( pattern ) ) {
     return sb.toString();
    }
  }
  ch = ( char )in.read();
 }
 }
 catch( Exception e ) {
 e.printStackTrace();
 }
 return null;
}

用于发送命令

    public void write( String value ) {
 try {
 out.println( value );
 out.flush();
 System.out.println( value );

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

用于插入用户名等

       public static void main( String[] args ) {


   try {
 telnetsample telnet = new telnetsample( "ip", 
                     "user", 
                     "password",
             "command");


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

   System.exit(0);
   Runtime.getRuntime().exit(0);

  }
 }

1 个答案:

答案 0 :(得分:0)

  1. 在构造函数中创建FileOutputStream
  2. 您在代码中System.out.println()的位置添加一行写入输出流。