【问题标题】:save the output from telnet保存 telnet 的输出
【发布时间】:2013-09-15 00:42:33
【问题描述】:

我已经用 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);

  }
 }

【问题讨论】:

  • 代码中两个 exit(0)有什么用?

标签: java string telnet


【解决方案1】:
  1. 在构造函数中创建FileOutputStream
  2. 就在您在代码中执行System.out.println() 的位置添加一行写入输出流的行。

【讨论】:

    猜你喜欢
    • 2021-07-13
    • 2014-01-25
    • 1970-01-01
    • 2014-10-19
    • 2011-07-07
    • 1970-01-01
    • 2011-07-15
    • 2021-04-20
    • 2013-01-07
    相关资源
    最近更新 更多