Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / First Aid / March 2005

Tip: Looking for answers? Try searching our database.

Capturing output from a command

Thread view: 
J - 20 Mar 2005 03:55 GMT
I think I may have bitten off more than I can handle here but I thought it
would be interesting to try to write a Java program to parse my firewall log
and do traceroutes on all the IP addresses.  I've done pretty well with it
so far, but the command that I am using, while it runs fine from the dos
prompt does not do what I expected it to when I run the code in my class.

Here is the method I have written to do the traceroutes.  Basically, there's
an input file containing IP addresses and an output file where I store the
results.
I hate the way OE formats things when they come from Text Pad.
The line where I show what is executing is showing me a command that works
in the dos command window but the file I'm writing to does not
get created when the program runs....  Can anyone give me any ideas why not?
public static void traceIPs(String fileName, String outFileName)

{

      if ((fileName == null) || (fileName == ""))

           throw new IllegalArgumentException();

           String line;

           String command;

           try

               {

                       BufferedReader in = new BufferedReader(new
FileReader(fileName));

                       if (!in.ready())

                               throw new IOException();

                       while ((line = in.readLine()) != null)

                               {

                                   try

                                   {

                                           command =
"C:/WINDOWS/system32/tracert.exe " + line + " >> " + outFileName;

                                            System.out.println("Executing:
" + command);

                                           Process tracert_proc =
Runtime.getRuntime().exec(command);

                                           InputStream cmdout =
tracert_proc.getInputStream();

                                            int x;

                                           while (( x = cmdout.read())
!= -1)

                                           {

                                                   //System.out.print(x);

                                           }cmdout.close();

                                      } catch (IOException e)

                               {

                                           System.out.println("I died" +
"\n");

                   }

       }

           in.close();

   }

           catch (IOException e)

           {

                   System.out.println(e);

           }

   }
Anthony Borla - 20 Mar 2005 05:55 GMT
> I think I may have bitten off more than I can handle here but
> I thought it would be interesting to try to write a Java program
[quoted text clipped - 12 lines]
> file I'm writing to does not get created when the program
> runs....  Can anyone give me any ideas why not?

Below you will find a [*** very rough ***] modified version of your code
that captures your command's output and both appends it to a StringBuffer,
and outputs it to a file [both shown for illustration purposes - choose
whichever method you wish]. You might also want to do some more reading on
'Process' for other command-line options, and process control features.

May I point out that unless this is purely a Java learning exercise, or you
later intend adding other Java-specific features [e.g. GUI-interface etc]
that Java is not really the ideal tool for this type of task [in fact, it
would probably be overkill, and much of Java's 'power' would be wasted].
You'd probably be better off using a scripting facility - the Win32 batch
language [on NT, Win2K and XP - issue a 'for/?' and 'set/?' at the command
line for syntax help] is actually quite well suited to this type of task, as
are third party tools such as sed / grep and gawk.

I hope this helps.

Anthony Borla

// ------------------------------------------
import java.io.*;

public class TraceIP
{
 public static void main(String[] args)
 {
   TraceIP.traceIP("in.txt", "out.txt");
 }

 public static void traceIP(String fileName, String outFileName)
 {
   if ((fileName == null) || (fileName == ""))
     throw new IllegalArgumentException();

   if ((outFileName == null) || (outFileName == ""))
     throw new IllegalArgumentException();

   String line, command;

   try
   {
     BufferedReader in =
             new BufferedReader(new FileReader(fileName));

     // Output file
     BufferedWriter out =
             new BufferedWriter(new FileWriter(outFileName));

     if (!in.ready()) throw new IOException();

     while ((line = in.readLine()) != null)
     {
       try
       {
         command = "tracert.exe " + line;
         System.out.println("Executing: " + command);

         Process tracert_proc =
               Runtime.getRuntime().exec(command);
         tracert_proc.waitFor();

         BufferedReader cmdout =
            new BufferedReader(
                new InputStreamReader(tracert_proc.getInputStream()));

         String oline;
         StringBuffer tmpCommandOutput = new StringBuffer();

         while ((oline = cmdout.readLine()) != null)
         {
           // Writes output to a string
           tmpCommandOutput.append(oline).append("\n");

           // Writes output to an output file
           out.write(oline, 0, oline.length()); out.newLine();
         }

         // Display output string
         System.out.print(tmpCommandOutput.toString());

         cmdout.close();
       }

       catch (InterruptedException e) {}
       catch (IOException e)
       {
         System.out.println("I died" + "\n");
       }

     }

     in.close(); out.close();
   }

   catch (IOException e)
   {
     System.out.println(e);
   }

 }
}
J - 20 Mar 2005 14:16 GMT
Top posting or bottom posting?  I don't wish to be flamed...

Yeah, this is just me playing around with Java.  I took a course and I
figured if I don't use it, I'll loose it.  I'm much more comfortable in AWK,
sed and ksh and have written something similar using such scripting
languages  (I'm a Unix guy by trade).

>> I think I may have bitten off more than I can handle here but
>> I thought it would be interesting to try to write a Java program
[quoted text clipped - 116 lines]
>  }
> }
Anthony Borla - 20 Mar 2005 23:30 GMT
> Top posting or bottom posting?  I don't wish to be
> flamed...

Well, in this instance, you top posted, and it is generally not seen as a
sensible way to respond as it lacks context - the reader, who may not be the
intended message recipient, will likely experience difficulty decoding the
message since lots of scrolling may be required in order to obtain the
necessary context.

Also, it is generally considered sensible to trim a response to include only
the immediately relevant details. Thus, excising the earlier-posted code
from your response would have been prudent.

Anyway, lecture [part 1] over ;) !

> Yeah, this is just me playing around with Java.  I took a course
> and I figured if I don't use it, I'll loose it.  I'm much more
> comfortable in AWK, sed and ksh and have written something
> similar using such scripting languages  (I'm a Unix guy by trade).

Yes, I had the feeling it might be a Java exercise, and that you may have
had scripting experience [newbies aren't usually interested in traceroutes
are they :) ?]. Given your *NIX experience, and the fact that you also work
on the Win32 platform:

* You probably know there are native Win32 versions of
   the more common *NIX utilities; try: http://unxutils.sourceforge.net/
   Sorry, I'm not a Cygwin fan

* The Win32 batch language is now a surprisingly powerful
  command language - certainly not as elegant as 'bash', but
  it now supports arithmetic / bitwise operations, interactive
  I/O, command substitution, and tokenising ala 'awk' - but
  easy to use and a standard offering on that platform

Still, the reason I mentioned alternatives to Java for the 'traceroute' task
is that USENET abounds with examples in which Java has been used for little
more than invoking a command utility, somehow tokenising the resultant
output, then redirecting it to a file. Java can certainly handle this type
of task [and certainly do it well], however, it really is the province of
scripting languages which can probably do it using less code, and with much
less overhead [no JVM to load].

After all, part of getting a job done right is choosing the appropriate
tool. Whilst Java has many excellent qualities, platform-specific tasks
really aren't its strong suite [not without a lot of work, anyway].

Anyway, lecture [part 2] over ;) !

<SNIP>

Finally, enjoy your Java programming. I highly recommend the tutorials here:

   http://java.sun.com/docs/books/tutorial/index.html

Working through them should keep you happily challenged for quite a while :)
!

Cheers,

Anthony Borla
Wiseguy - 20 Mar 2005 23:55 GMT
"J" <squibbies43@hotmail.com> scribbled on the stall wall:
> Top posting or bottom posting?  I don't wish to be flamed...

Well, then don't top-post...K?

> Yeah, this is just me playing around with Java.  I took a course and I
> figured if I don't use it, I'll loose it.  I'm much more comfortable in AWK,
> sed and ksh and have written something similar using such scripting
> languages  (I'm a Unix guy by trade).

Since JAVA is not the prefered tool to do this, I would hope it is only
an exercise.  A better common tool to do this would have been PERL.  The
whole perl script could probably be written in fewer lines than you
have total fingers on your hands.
J - 21 Mar 2005 03:00 GMT
> Since JAVA is not the prefered tool to do this, I would hope it is only
> an exercise.  A better common tool to do this would have been PERL.  The
> whole perl script could probably be written in fewer lines than you
> have total fingers on your hands.

Now that the rules have been established... bottom posting it is.
After some respectful snipping, I have used Uwin and would love to be able
to use SFU but it doesn't run on XP Home... ick
As for the Java Tutorial.. I've spent some time wandering around there,
hoping to re-inforce what I've learned in my class.  The reason I chose the
traceroute was that I did something similar using awk and ksh (under Uwin)
that I just wanted to see how much work it would take to write something
similar in Java.  And if you are interested in the code,

#!/usr/bin/ksh
grep "^Remote" $1 | grep "local service is" | grep -v "ftp" |
/usr/bin/cut -c34-55 > temp1
/usr/bin/awk -F, '{ print $1 }' temp1 > temp2
/usr/bin/sort -u temp2 > temp3
for ip in `/usr/bin/cat temp3`
do
 tracert $ip
done > $2
rm -f temp*

Your comment on Perl is noted... however I have not found a tutorial online
which will allow me to learn the language with practical examples...any
recommendations?

> ----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet
> News==----
> http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+
> Newsgroups
> ----= East and West-Coast Server Farms - Total Privacy via Encryption
> =----
Wiseguy - 21 Mar 2005 05:40 GMT
"J" <squibbies43@hotmail.com> scribbled on the stall wall:
> Your comment on Perl is noted... however I have not found a tutorial online
> which will allow me to learn the language with practical examples...any
> recommendations?

getting extremely OT for this group but no, I can't recommend any
tutorials for perl.  I'd suggest perl.org website and see where you
end up.


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.