How to run exec from Java for netsh? - java

The following works fine when i type it in directly into cmd.exe:
netsh wlan connect name="Profile Name" ssid=XXXXXX
However when i try to do this from java it does not work, neither does it throw any exception. It is silently ignored:
Runtime.getRuntime().exec("cmd netsh wlan connect name=\"Profile Name\" ssid=XXXXX ") ; `
How can i improve the code ?

First try removing the cmd parameter (you don't need to run this interpreter, just netsh).
Else it may be due to whitespace characters in this command line (be careful of whitespace in SSID for example). You may want to try Runtime.exec(String[] cmdarray) or java.lang.ProcessBuilder instead to specify each parameter individually.
Examples:
Runtime.getRuntime().exec(new String[] {"netsh", "wlan", "connect", "name=\"Profile Name\"", "ssid=XXXXX"});
or (complete example):
ProcessBuilder pb = new ProcessBuilder("netsh", "wlan", "connect",
"name=\"Profile Name\"", "ssid=XXXXX");
pb.redirectErrorStream(true);
Process process = pb.start();
BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}

Related

Runtime.exec() returning null

I have seen similiar questions on this site, but none of them seem to address/solve my problem, so I figured there is something specifically wrong with my program. I am trying to execute a very simple command, which is to take a string of a process name from a textfield input and concatenate it to a command to return and print the title of the window. This is my code:
String line;
Process p = null;
try
{
String command = "tasklist /v /fo list /fi \"imagename eq " + tf.getText().trim() + "*\"| find /i \"window title:\"\n";
p = Runtime.getRuntime().exec(command);
BufferedReader input =
new BufferedReader(new InputStreamReader(p.getInputStream()));
System.out.println(command);
while ((line = input.readLine()) != null)
{
line = line.trim();
System.out.println(line);
}
System.out.println("done");
}
catch (IOException ioException)
{
ioException.printStackTrace();
}
However, the line returned by the InputStream is always null, even though if I put the command used in .exec() into cmd (I printed it so I know they are the exact same), it works properly, albeit after a 5 seconds or so of delay. I tried it with 2 different process names and they both worked on cmd, but not in this java program. This is the output of the above code, in case that helps (the blank line is presumably from the \n at the end of the command string):
tasklist /v /fo list /fi "imagename eq notepad*"| find /i "window title:"
done
I tried adding p.waitFor() after calling .exec(), but that didn't seem to change anything. So what am I doing wrong here?
You have two problems with launching the command. Firstly you are ignoring error stream so don't see the actual problem.
Replace p = Runtime.getRuntime().exec(command); with ProcessBuilder to get access to error message:
ProcessBuilder pb = new ProcessBuilder(command);
pb.redirectErrorStream();
p = pb.start();
This will tell you that tasklist is not a process. Normally using full pathname would fix this type of error, but as you are using pipe the whole command must sent to to CMD.EXE to interpret pipe components correctly. Run CMD.EXE then your piped command:
ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/c", command);
pb.redirectErrorStream();
p = pb.start();
Prints:
tasklist /v /fo list /fi "imagename eq notepad*"| find /i "window title:"
Window Title: Notepad++
done
It's also easier to read STDOUT with simple transfer:
try(var stdout = p.getInputStream()) {
stdout.transferTo(System.out); // or where-ever
}

Fetching errors after running grep command from java

I am running grep command via my Java program. Running grep on the command line sometimes writes an error on stderr of the kind: No such file or directory. I want to detect in my Java program whenever this error happens as a result of executing the grep command via the program. How can I achieve this goal of mine? This is what I've written so far:
Runtime rt = Runtime.getRuntime();
String[] cmd = {"/bin/sh", "-c", "grep -c 'Search_String' /path/to/file(s)/being/searched"};
Process proc = rt.exec(cmd);
BufferedReader is = new BufferedReader(new
InputStreamReader(proc.getInputStream()));
String line;
while ((line = is.readLine()) != null) {
System.out.println(line);
}
You can detect if the process returned with an error; as #Dakoda mentions, exitValue() won't have the exit value until the process ends, but using waitFor() will block until the process ends and returns the exit value:
int rv = rt.waitFor();
if (rv != 0) { ... }
Error output is usually on stderr rather than stdout, so to read errors you'd use:
BufferedReader is = new BufferedReader(
new InputStreamReader(proc.getErrorStream()));

Run exec file using Java on Mac

I need to start a server using bash, so I had created an UNIX shell , but I am not able to execute it with Java from Eclipse.
I tried the following code which doesn't work :
Process proc = Runtime.getRuntime().exec(./startServer);
Here is content of the startServer file :
#!/bin/bash
cd /Users/sujitsoni/Documents/bet/client
npm start
You can try the following two options.
Option 1
Process proc = Runtime.getRuntime().exec("/bin/bash", "-c", "<Abosulte Path>/startServer");
Option 2
ProcessBuilder pb = new ProcessBuilder("/bin/bash", "-c", "<Absolute Path>/startServer");
pb.directory(new File("<Absolute Path>"));
Process proc = pb.start();
A couple Of things can go wrong:
The path to the file you have given might be wrong for eclipse it can take relative path but from the command line, it will take the absolute path.
error=13, Permission denied - If the script file doesn't have required permissions. In your scenario, that might not the case as you are not getting any error.
At last, you are executing the script by java program so the output of your script will not be printed out. In your scenario, this might be the case. You need to capture the output of script from BufferedReade and print it. ( In your case server might have started but you are not seeing the logs/output of the script.
See the code sample below for printing output.
public static void main(String[] args) throws IOException, InterruptedException {
Process proc = Runtime.getRuntime().exec("./startServer");
proc.waitFor();
StringBuffer output = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = "";
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}
System.out.println(output);
}

How to execute Python script from Java (via command line)?

I can execute Linux commands like ls or pwd from Java without problems but couldn't get a Python script executed.
This is my code:
Process p;
try{
System.out.println("SEND");
String cmd = "/bash/bin -c echo password| python script.py '" + packet.toString() + "'";
//System.out.println(cmd);
p = Runtime.getRuntime().exec(cmd);
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String s = br.readLine();
System.out.println(s);
System.out.println("Sent");
p.waitFor();
p.destroy();
} catch (Exception e) {}
Nothing happened. It reached SEND but it just stopped after it...
I am trying to execute a script which needs root permissions because it uses serial port. Also, I have to pass a string with some parameters (packet).
You cannot use the PIPE inside the Runtime.getRuntime().exec() as you do in your example. PIPE is part of the shell.
You could do either
Put your command to a shell script and execute that shell script with .exec() or
You can do something similar to the following
String[] cmd = {
"/bin/bash",
"-c",
"echo password | python script.py '" + packet.toString() + "'"
};
Runtime.getRuntime().exec(cmd);
#Alper's answer should work. Better yet, though, don't use a shell script and redirection at all. You can write the password directly to the process' stdin using the (confusingly named) Process.getOutputStream().
Process p = Runtime.exec(
new String[]{"python", "script.py", packet.toString()});
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(p.getOutputStream()));
writer.write("password");
writer.newLine();
writer.close();
You would do worse than to try embedding jython and executing your script. A simple example should help:
ScriptEngine engine = new ScriptEngineManager().getEngineByName("python");
// Using the eval() method on the engine causes a direct
// interpretataion and execution of the code string passed into it
engine.eval("import sys");
engine.eval("print sys");
If you need further help, leave a comment. This does not create an additional process.
First, open terminal and type "which python3". You will get the complete path of python3. For example "/usr/local/bin/python3"
String[] cmd = {"/usr/local/bin/python3", "arg1", "arg2"};
Process p = Runtime.getRuntime().exec(cmd);
p.waitFor();
String line = "", output = "";
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = br.readLine())!= null) {sb = sb.append(line).append("\n"); }
output = sb.toString();
System.out.println(output);

Running cmd with spaces from java

I want to run a command through java session. The command contains spaces. as
"C:\With Space\sample.exe" -command_option "C:\Source File\test.c"
This works if
C:\WithoutSpace\sample.exe -command_option "C:\Source File\test.c"
if we keep the quotes in C:\With Space\sample.exe we get error as :'The filename, directory name, or volume label syntax is incorrect.' and if we remove the quotes then the exe do not run...
please guide.
Thanks,
Try this:
String[] arg = {"cmd","/c","C:/Source File/test.c"};
ProcessBuilder pb = new ProcessBuilder(arg);
Process pr = pb.start();
Also, you can use Runtime.exec(String[]) version
Example:
Runtime rt = Runtime.getRuntime();
String[] args = { "cmd", "/c", "C:/Source File/test.c"};
try
{
Process proc = rt.exec(processCommand);
}
You can try this:
Process process = Runtime.getRuntime().exec("'C:\WithoutSpace\sample.exe' -command_option 'C:\Source File\test.c'");
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
while ((line = in.readLine()) != null) {
//line contain command output
}

Categories

Resources