0

I am executing Nmap in Java which saves network information to a file. The code looks like this:

Process p = Runtime.getRuntime().exec(new String[] {"nmap", "-O", "-oX", nmapFileLocation, ipStr+"/24"});

BufferedReader in = new BufferedReader(  new InputStreamReader(p.getInputStream()));  
String line = null;  while ((line = in.readLine()) != null) {}   
p.waitFor();

OutputStream  os = p.getOutputStream(); os.flush();  
os = p.getOutputStream(); os.flush();

It seems I have to read through all of the lines to get it to work (I'm referring to the while loop); this worked for smaller networks. I tried several things to get it to run on larger networks, but it seems to hang.

For example, I am currently running the Java application that executes nMap. It has been running for half an hour and is hung where the nmap lines of code are. I have observed (many times) that if I open the file that it created, while the Java application is running, I only see the first ~12 lines in the newly-created file. However, as soon as I shut down the Java application, all ~1600 lines of the file are visible. I am willing to experiment with different approaches.

John R
  • 2,920
  • 13
  • 48
  • 62
  • Have a look at the ProcessBuilder class. Maybe you forget to close a stream somewhere. Isn´t there an ErrorStream also which you should handle? – HectorLector Dec 20 '11 at 00:07
  • 1
    HectorLector is right. You also need to consume the error stream. The answer to ["Capturing stdout when calling Runtime.exec"](http://stackoverflow.com/questions/882772/capturing-stdout-when-calling-runtime-exec) may help you out. – creemama Dec 20 '11 at 00:39

1 Answers1

0

John,

try apache commons-exec.

Once it helped to me, may help to you.

Here is why (from their site):
Executing external processes from Java is a well-known problem area. It is inheriently platform dependent and requires the developer to know and test for platform specific behaviors, for example using cmd.exe on Windows or limited buffer sizes causing deadlocks.

"You look at Commons Exec and think "Wow - calling Runtime.exec() is easy and the Apache folks are wasting their and my time with tons of code". Well, we learned it the hard way (in my case more than once) that using plain Runtime.exec() can be a painful experience. Therefore you are invited to delve into commons-exec and have a look at the hard lessons the easy way ..."

andrey
  • 842
  • 4
  • 6