executing a python script on windows using java Runtime.exec - java

I have a python script that runs on windows and uses win32 extensions and WMI to get some information. If I run the script using the command line, it executes perfectly. But, if I try to run the same script using java Runtime.exec("python myscript.py") it seems to get blocked on the waitFor(). The code is like this:
Process p = Runtime.getRuntime().exec("python myscript.py");
int exitCode = p.waitFor();
If I try to use this same java code with some very simple python script like
print "hello world"
I get the exitCode to be 0, which means it works. Can I execute a python script that imports WMI library, using java Runtime.exec()?
Thanks

One likely reason is that your IO buffers are full and need to be flushed, so try flushing both stdout and stderr from your Process in the java code (example code).
Alternatively, you could try redirecting all output to NUL or a text file with one of the following arguments to exec:
cmd.exe /c python myscript.py > NUL 2>&1
cmd.exe /c python myscript.py > output.txt 2>&1

Related

Unable to use Bash's "-i" option from ProcessBuilder

The goal of my program is to run an interactive command line executable from Java, so I can add input partway through when required. Basically redirecting input.
I couldn't find anything that worked online because the -c flag does not allow interactivity, but then I saw that the -i flag in the terminal allowed me to run commands with interactive input if I fed it a .sh file.
However, when I tried using this flag in java, it didn't work. I have separate input and output threads, so if I could get this to work it seems like it would be easy.
Relevant code:
ProcessBuilder pb = new ProcessBuilder()
.directory(new File(testDir))
.inheritIO()
.command("bash", "-i"
,"executor.sh");
proc = pb.start();
this is the error i get:
bash: cannot set terminal process group (1469): Inappropriate ioctl for device
bash: no job control in this shell
If there's way I could get this -i option working, then I'd appreciate pointers to something else that would allow me to get interactive input working because nothing else that I've tried seems to solve this problem.
bash -i is completely unrelated to ability to read from the TTY.
Rather, redirect from the TTY, after your script already started:
#!/usr/bin/env bash
exec </dev/tty || { echo "ERROR: Unable to connect stdin to /dev/tty" >&2; exit 1; }
read -r -p "Fill out this prompt please: " value
echo "Read from TTY: $value"
The command exec </dev/tty replaces the script's stdin (FD 0) with a read handle on /dev/tty. If you wanted to do this just for a single command, rather than for the whole script, put </dev/tty on the end of that command.
Of course, this only works if your process is run in a context where it has a controlling terminal at all -- but if that weren't the case, you couldn't read from the user without getting some kind of handle on an I/O device regardless.

Logging in into shell as sudo user and executing shell through java

i have a shell file that needs to be executed through java program. But, the problem is the shell file is n't getting executed because usually we run shell files through command line after executing the sudo command which in turn asks for password.Is there any possibility that i can execute the shell using Runtime.exec("ksh path-to-shell-file") by-passing the sudo command.
You can write commands to the outStream of the process from Runtime.exec();
Get the outStream, write a command to it, and then write "\r\n" to it to execute.
So basically treat the process as a console, and write commands to it like to normal console. Obviously you can also get the in and err streams

bash array declaration or slice does not work with ProcessBuilder

I have this easiest bash script
arr=('one' 'two' 'three' 'four');
echo "${arr[#]:2}" > test.txt
(in fact i want to used ${#:2})
If I run this script in command line with ./my_script.sh, it work as expected. But when I try to use a java ProcessBuilder, the test.txt file is never created. (in fact the bash script stop the execution at the slice).
ProcessBuilder pb = new ProcessBuilder("./my_script.sh");
pb.start();
i tried with a lot of other command in my bash script and everything work fine with processBuilder, all exept the "${#:2}".
for exemple this script work fine and create test.txt in my project directory
echo "test" > test.txt
Someone know why?

How to execute unix commands through Windows/cygwin using Java

I am trying to accomplish two things:
I am running cygwin on Windows7 to execute my unix shell commands and I need to automate the process by writing a Java app. I already know how to use the windows shell through Java using the 'Process class' and Runtime.getRuntime().exec("cmd /c dir"). I need to be able to do the same with unix commands: i.e.: ls -la and so forth. What should I look into?
Is there a way to remember a shell's state?
explanation: when I use: Runtime.getRuntime().exec("cmd /c dir"), I always get a listing of my home directory. If I do Runtime.getRuntime().exec("cmd /c cd <some-folder>") and then do Runtime.getRuntime().exec("cmd /c dir") again, I will still get the listing of my home folder. Is there a way to tell the process to remember its state, like a regular shell would?
It seems that the bash command line proposed by PaĆ­lo does not work:
C:\cygwin\bin>bash -c ls -la
-la: ls: command not found
I am having trouble figuring out the technicalities.
This is my code:
p = Runtime.getRuntime().exec("C:\\cygwin\\bin\\bash.exe -c ls -la");
reader2 = new BufferedReader(new InputStreamReader(p.getInputStream()));
line = reader2.readLine();
line ends up having a null value.
I added this to my .bash_profile:
#BASH
export BASH_HOME=/cygdrive/c/cygwin
export PATH=$BASH_HOME/bin:$PATH
I added the following as well:
System Properties -> advanced -> Environment variables -> user variebales -> variable: BASH, value: c:\cygwin\bin
Still nothing...
However, if I execute this instead, it works!
p = Runtime.getRuntime().exec("c:\\cygwin\\bin\\ls -la ~/\"Eclipse_Workspace/RenameScript/files copy\"");
1. Calling unix commands:
You simply need to call your unix shell (e.g. the bash delivered with cygwin) instead of cmd.
bash -c "ls -la"
should do. Of course, if your command is an external program, you could simply call it directly:
ls -la
When starting this from Java, it is best to use the variant which takes a string array, as then
you don't have Java let it parse to see where the arguments start and stop:
Process p =
Runtime.getRuntime().exec(new String[]{"C:\\cygwin\\bin\\bash.exe",
"-c", "ls -la"},
new String[]{"PATH=/cygdrive/c/cygwin/bin"});
The error message in your example (ls: command not found) seems to show that your bash can't find the ls command. Maybe you need to put it into the PATH variable (see above for a way to do this from Java).
Maybe instead of /cygdrive/c/cygwin/bin, the right directory name would be /usr/bin.
(Everything is a bit complicated here by having to bridge between Unix and Windows
conventions everywhere.)
The simple ls command can be called like this:
Process p = Runtime.getRuntime().exec(new String[]{"C:\\cygwin\\bin\\ls.exe", "-la"});
2. Invoking multiple commands:
There are basically two ways of invoking multiple commands in one shell:
passing them all at once to the shell; or
passing them interactively to the shell.
For the first way, simply give multiple commands as argument to the -c option, separated by ; or \n (a newline), like this:
bash -c "cd /bin/ ; ls -la"
or from Java (adapting the example above):
Process p =
Runtime.getRuntime().exec(new String[]{"C:\\cygwin\\bin\\bash.exe",
"-c", "cd /bin/; ls -la"},
new String[]{"PATH=/cygdrive/c/cygwin/bin"});
Here the shell will parse the command line as, and execute it as a script. If it contains multiple commands, they will all be executed, if the shell does not somehow exit before for some reason (like an exit command). (I'm not sure if the Windows cmd does work in a similar way. Please test and report.)
Instead of passing the bash (or cmd or whatever shell you are using) the commands on the
command line, you can pass them via the Process' input stream.
A shell started in "input mode" (e.g. one which got neither the -c option nor a shell script file argument) will read input from the stream, and interpret the first line as a command (or several ones).
Then it will execute this command. The command itself might read more input from the stream, if it wants.
Then the shell will read the next line, interpret it as a command, and execute.
(In some cases the shell has to read more than one line, for example for long strings or composed commands like if or loops.)
This will go on until either the end of the stream (e.g. stream.close() at your side) or executing an explicit exit command (or some other reasons to exit).
Here would be an example for this:
Process p = Runtime.getRuntime().exec(new String[]{"C:\\cygwin\\bin\\bash.exe", "-s"});
InputStream outStream = p.getInputStream(); // normal output of the shell
InputStream errStream = p.getInputStream(); // error output of the shell
// TODO: start separate threads to read these streams
PrintStream ps = new PrintStream(p.getOutputStream());
ps.println("cd /bin/");
ps.println("ls -la");
ps.println("exit");
ps.close();
You do not need cygwin here. There are several pure Java libraries implementing SSH protocol. Use them. BTW they will solve your second problem. You will open session and execute command withing the same session, so the shell state will be preserved automatically.
One example would be JSch.

Invoking shell from java, it complaints "stty: standard input: Invalid argument"

I invoke a shell command by Process class from java and it prints
"stty: standard input: Invalid argument"
no matter whether the command is right or wrong (normal output of shell command is shown too). If I run the shell command in shell, no such error message is shown.
The command is something like this: {"/bin/csh", "-c", "echo hello"}
You are invoking the stty command from your .profile, or .bash_profile. You'll have to redirect its standard error to /dev/null.
stty blah blah blah 2>/dev/null
stty can't deal with the pseudo-tty that Java provides in shelling out.
Try using the -f option of csh to disable the reading of the .chsrc and .login files:
{"/bin/csh", "-cf", "echo hello"}
Quoth the documentation for java.lang.Process:
"The methods that create processes may
not work well for special processes on
certain native platforms, such as
native windowing processes, daemon
processes, Win16/DOS processes on
Microsoft Windows, or shell scripts.
The created subprocess does not have
its own terminal or console."
Perhaps you would like the java.lang.ProcessBuilder, instead.
Have you look here.
I managed to run some commands like this

Categories