Kishore Reddy
Kishore Reddy

Reputation: 926

Execute windows command in Java

Need to run netstat -n | find ":3389" | find "ESTABLISHED" command using Java Runtime.

Tried like: Runtime.getRuntime().exec(cmd); but we can't do this if we have | (pipe) in our command.

I had found for linux command we can costruct like: String[] cmd = {"/bin/sh", "-c", "grep -c 'Report Process started' /path/to/server.log"}; Runtime.getRuntime().exec(cmd); but I need for windows, please let me know how we can do?

Upvotes: 1

Views: 2664

Answers (2)

Kishore Reddy
Kishore Reddy

Reputation: 926

In Windows we can achieve this like:

String[] cmd = { "cmd.exe", "/c",
                    "netstat -n | find \":3389\" | find \"ESTABLISHED\"" };
Process process = new ProcessBuilder(cmd).start();

Upvotes: 0

Liviu Stirb
Liviu Stirb

Reputation: 6075

You should run only netstat -n and do the rest in java. You could also write a script, and execute the script instead of separate commands. If you really need to do everything in a single line that has pipes the command must be prefixed with cmd /C

Upvotes: 1

Related Questions