I tried to execute the following docker command from Java code:
command: ***docker exec -it reverent_hoover date***
(Here, reverente_hoover is the container name.)
When I executed the above command from Linux, it gave me the following output:
Wed May 6 05:19:28 UTC 2015
But when I tried to execute it from Java code, it gave me this error:
time="2015-05-05T19:31:19+05:30" level="fatal" msg="cannot enable tty
mode on non tty input"
I don't know how to solve this problem.
Issue 10734 mentions:
The java process is not providing a TTY to the docker CLI but you've asked for a TTY by specifying -t in your command.
So, does the image actually need a TTY? If not, don't specifiy -t... if the image doesn't need stdin at all don't specify -i either.
If it does need the TTY, then you'll need to setup the TTY for your command and it should work.
For example, see "persistent local tty session with java"
Instead of Runtime.getRuntime().exec("command"); do Runtime.getRuntime().exec("/bin/sh"); and hold on to the Process object
"Runtime.exec with Unix console programs" illustrates that in the context of using less:
Process p = Runtime.getRuntime().exec(new String[] {"sh", "-c",
"less >/dev/tty"});
OutputStream out = p.getOutputStream();
out.write("Lengthy message".getBytes());
out.close();
System.out.println("=> "+p.waitFor());
Related
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.
I am trying to start a new process using Runtime.exec(), but my problem lies within using ssh to remote in and then run a java program there. Code:
test = "ssh -t username#host java packageName.ClassName portNumber (Other command line args for this class)"
Process proc = Runtime.getRuntime().exec(new String[] {"/bin/bash", "-c", test});
this doesn't fail or catch, but I need to be able to see the stdout for the newly running process and I don't.
Note: if I run ssh -t username#host java packageName.ClassName portNumber (Other command line args for this class) from the command line it works fine. I have the host setup to not require a password by using ssh keys.
Any ideas?
You need to use Process.getInputStream to obtain the output from the sub-process being created.
See this article for a good discussion on Runtime.exec.
I think you can ask for an input stream that corresponds to the stdout of the process and then print it on your standard output. If you need to see it after it executes, just call waitFor() method on the process so it finishes before you start printing.
Use getInputStream() to access returned process's stdout. You can also use facilities provided by ProcessBuilder.Redirect.
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.
I'm moving our servlets (pure Java, running in Tomcat 6) from CentOS to Debian, and faced the problem with executing commands with Runtime.exec().
(The command should be ImageMagick's convert in production, but I have simplified the calls to find the source of problems, so all the following code with echo is tested and not working as well).
String command = "echo test123 > /tmp/tomcat6-tmp/1";
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(command);
int exitVal = process.waitFor();
Seems to be pretty common way to call an external program. It does run, returns 0 in exitVal, but fails to create file and put text in it.
So does low-level approach:
ProcessBuilder pb = new ProcessBuilder("echo", "test123 > /tmp/tomcat6-tmp/3");
Process process = pb.start();
int resInt = process.waitFor();
But it is possible to create a file and put some text in it using Java code placed in the same method:
String fname = "/tmp/tomcat6-tmp/2";
File file = new File(fname);
file.createNewFile();
FileWriter fileWriter = new FileWriter(file);
fileWriter.write("test123");
fileWriter.close();
Runtime.exec("whoami") successfully returns tomcat6, the folder /tmp/tomcat6-tmp/ does exist, all permissions are set correctly.
$ ls -al /tmp/tomcat6-tmp/
total 60
drwxr-xr-x 2 tomcat6 root 4096 Mar 2 15:26 .
drwxrwxrwt 6 root root 4096 Mar 2 15:25 ..
-rw-r--r-- 1 tomcat6 tomcat6 7 Mar 2 15:26 2
All commands without need to access files in system are seem to execute normally with Runtime.exec() in the same context.
I use fresh install of debian squeeze with tomcat6 installed from packages, without any modifications in configuration:
$ aptitude show tomcat6
Package: tomcat6
State: installed
Version: 6.0.28-9+squeeze1
.....
$ cat /etc/issue
Debian GNU/Linux 6.0 \n \l
How can I solve the issue?
Or at least where should I look? I've googled every imaginable reason for Java to misbehave this way, but failed to find a clue.
P.S. As this is default installation, Java security manager is disabled in /etc/init.d/tomcat6
# Use the Java security manager? (yes/no)
TOMCAT6_SECURITY=no
Put the action you want into a single executable shell script, then exec the shell script.
Java's Runtime.exec() is a wrapper around the exec system call, which will run the process directly, rather than under a sub-shell. The > redirection is carried out by the shell, and will not work as an argument to a directly execed process.
Don't know if this "echo test123 > /tmp/tomcat6-tmp/1" can be run as one command. I remember that I had similar problem and I had to split it, so try to run "echo test123" and then obtain an input stream with the output of the command. If you have a stream you can easily write to file.
Moreover, you execute command with args so try to use method that takes array as a parameter.
I have a simple server application, which I would like to run in the background. The following line works for me:
Runtime.getRuntime().exec("cmd /c start java -jar ..\\server\\server.jar -Dlog4j.configuration=file:src\\test\\resources\\log4j.properties -filename src\\test\\resources\\server.properties");
But it displays the cmd window and I am unable to destroy it. So I would like to use
Runtime.getRuntime().exec("java -jar ..\\server\\server.jar -Dlog4j.configuration=file:src\\test\\resources\\log4j.properties -filename src\\test\\resources\\scIntegration.properties");
But it simply doesn't connect to the server. So why is that?
A related question. How do I end the process? It is a server that "doesn't end". So I have to kill it and I would assume, that running the java only command would be capable to be destroyed, but with the cmd I have no luck there.
You should split your command into an array in which first argument is the actual command to run and all the rest are command like arguments:
Runtime.getRuntime().exec(new String[] {"/usr/bin/java", "-jar", "..\\server\\server.jar" ...});
Try using an absolute path to the java programm.
For destroying: exec() returns a java.lang.Process, which you should be able to destroy. If not, you have to implement some type of callback to shut your server down, e.g. listening on a specific prot for a shutdown command.
The server is outputing something to stdout and in the shortened command version it didn't have a place to output, so it got stuck while trying to output some data. The solution is to pipe the stdout to eg some file.