path name and arguments of running processes using java code - java

I want to get the path name and arguments of running processes using java code. Is there any solution?

For instance, on Windows, one possibility is to encapsulate the system call to TASKLIST.EXE
Extract from the code:
Process p = Runtime.getRuntime().exec("tasklist.exe /fo csv /nh");
BufferedReader input = new BufferedReader
(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
if (!line.trim().equals("")) {
// keep only the process name
line = line.substring(1);
processes.add(line.substring(0, line.indexOf(""")));
}
}
You should use tasklist /V though, since it comes with the parameters of the processes.

You could use the SIGAR framework, which gives you native support for Linux, FreeBSD, Windows, Solaris, AIX, HP-UX and Mac OSX

Related

Running python from Java using Process Builder

For an existing Java code that I want to extend, I need to run a python code from within Java. I am using Process builder for this:
ProcessBuilder pb = new ProcessBuilder("python", "/directorypath/mypython.py");
Process p=pb.start();
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));
// read the output from the command
System.out.println("Here is the standard output of the command:\n");
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
System.exit(0);
}
While the code runs perfectly fine from command line, in Java I get a "We need BeautifulSoup, sorry" error. As far as I understand,this means Java environment is missing some sort of libraries but then the code works perfectly from command line.
Do I need to send some environment variables? If yes, what and how?
I have 'BeautifulSoup4' installed and it is up-to-date.
Not a definitive answer but this looks to me as a problem in the environment which this process runs in; it is probably missing some environment variables which are expected by python to find your "BeautifulSoup4" extension.
A ProcessBuilder has an .environment() method returning a Map<String, String> whose keys are the environment variables and whose values are those variables' values. NOTE THAT MODIFYING THIS MAP ACTUALLY ALTERS THE ENVIRONMENT! (the one of the process you will launch, that is).
Try and print your environment and compare it with what it is when you run from the command line.

When Runtime.getRuntime().exec call linux batch file could not find its physical directory [duplicate]

This question already has answers here:
How do I get the directory where a Bash script is located from within the script itself?
(74 answers)
Closed 8 years ago.
I have an java application.And I use Runtime.getRuntime().exec for call a batch file.When I call a linux batch file using with Runtime.getRuntime().exec the batch file could not find its own directory.
I use pwd command in batch file but it returns application path.
I need batch file's own physical path from itself.
How can I do this?
You must use a ProcessBuilder in order to acomplish that:
ProcessBuilder builder = new ProcessBuilder( "pathToExecutable");
builder.directory( new File( "..." ).getAbsoluteFile() ); //sets process builder working directory
Try this . Its working for me.
Process p = Runtime.getRuntime().exec("pwd");
BufferedReader bri = new BufferedReader
(new InputStreamReader(p.getInputStream()));
BufferedReader bre = new BufferedReader
(new InputStreamReader(p.getErrorStream()));
String line;
while ((line = bri.readLine()) != null) {
System.out.println(line);
}
bri.close();
while ((line = bre.readLine()) != null) {
System.out.println(line);
}
bre.close();
p.waitFor();
Batch files, if you're specifically referring to files with the '.bat' extension, are designed to be used with Microsoft's Command Prompt shell ('cmd.exe') in Windows, as they are script files containing a sequence of commands specifically for this shell, and as such will not work with Unix shells such as Bash.
Assuming you actually mean a Unix 'shell script', and not specifically a Microsoft 'batch file', you'd be better off using the ProcessBuilder class, as it provides greater flexibility than Runtime's exec() method.
To use ProcessBuilder to run a script in its own directory, set the builder's directory to the same directory that you're using to point to the script, like so:
// Point to wherever your script is stored, for example:
String script = "/home/andy/bin/myscript.sh";
String directory = new File(script).getParent();
// Point to the shell that will run the script
String shell = "/bin/bash";
// Create a ProcessBuilder object
ProcessBuilder processBuilder = new ProcessBuilder(shell, script);
// Set the script to run in its own directory
processBuilder.directory(new File(directory));
// Run the script
Process process = processBuilder.start();

Java ProcessBuilder: capture output from scripts run from scripts run from Java

Using Java's ProcessBuilder, I can run an external script, and redirect its output into my GUI.
Process proc = pb.start();
BufferedReader bri = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = "";
while (proc.isAlive())
{
// bri may be empty or incomplete.
while ((line = bri.readLine()) != null)
{
textArea.appendText(line);
}
}
Now, the script I am running also calls other scripts and processes. Two of these, that should be captured, are currently displayed in their own xterm windows. Is it possible to also capture these outputs, and display in a similar manner?.
If these outputs are being managed by your source script, I think it will work. Just as an advice, take a look in this article: When Runtime.exec() won't
It is extremammly important to read it to learn how to work with external processes correctly.

Java - Execute a .SH file

How would I go about executing a .SH file (this is localhost, no remote connection or anything)? I've seen lots of Runtime.exec and other things when I searched but those didn't seem to work.
This is Java 6. Also if it matters, all the SH is doing is moving two folders around.
Thanks!
You could use ProcessBuilder
ProcessBuilder pb = new ProcessBuilder("myshell.sh", "myArg1", "myArg2");
Process p = pb.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null)
{
System.out.println(line);
}
You may also give some consideration to the JSch library if you do not want to make your code platform-dependent by directly invoking OS commands.

External process launched with ProcessBuilder/Runtime.exec() fails on XP, works on Win 7

I am working on a Java program that has to fetch the machine serial number, CPU serial number etc. On Windows, the WMI interface is the best way to query for such information, and the standard way to query using the commandline is
wmic bios get serialnumber
which produces output:
SerialNumber
WWV46RT609A3467173E
Translating this into Java, I have used both Runtime.exec() and a ProcessBuilder like so:
(The commented Process p is what I did previously). Here, component and item correspond to 'bios' and 'serialnumber' in the commandline above.
String ret = "";
ProcessBuilder pb = new ProcessBuilder("wmic", component, "get", item);
pb.redirectErrorStream(true);
// Process p = Runtime.getRuntime().exec(
// "wmic " + component + " get " + item);
Process p = pb.start();
InputStreamReader isr = new InputStreamReader(p.getInputStream());
BufferedReader input = new BufferedReader(isr);
String str;
while ((str = input.readLine()) != null) {
if (str.equalsIgnoreCase(item) || StringUtils.isBlank(str)) {
continue;
}
ret = str.trim();
}
input.close();
isr.close();
System.out.println(ret);
This snippet works perfectly on Windows 7, but hangs on Windows XP. Using wmic from the commandline works on both OSes.
I read here that there's a problem with handling both stdout and stderr of the called process, hence the redirectErrorStream() call.
Why does it work flawlessly on Windows 7 but fail on XP? Is there a way other than spawning a separate thread, aka 'StreamGobbler'? (The linked example is quite ancient, and predates the ProcessBuilder class, with its redirectErrorStream() call.
I hope that you have by now got a resolution to this issue. If not, this is what you need to do. First, I also encountered with the same issues and came to discover that it is bufferedReader issue. It is gets into a deadlock situation that resulting into windows xp hanging. The solution is to simulate the end of line (eof) to the bufferedreader by appending "<NUL" the the command.
String[] command = {"CMD", "/C", "WMIC COMPUTERSYSTEM GET USERNAME <NUL "} and executing this command.
You have to use threads to capture ouputs (standard & error).
You can also take a look at this Apache library.

Categories

Resources