We are working on a requirement to execute shell commands from java swing UI.
We need to execute one command to start the session, once the session is started we need to execute some common commands repeatedly.
We are able to execute the commands using the below command.
Runtime.getRuntime().exec("setSession")
Runtime.getRuntime().exec("execute individual task");
this way, everytime we have to set the session and executing the individual tasks.
Is there any way to execute a command (like setSession) once and retain the session to execute the remaining commands?
If I got Your task right, You might want to start a shell on the underlying system, get it's input and output streams and issue Your commands there.
Though that makes You operation system dependent. But commands You executing probably are anyway.
Something like:
Process p = Runtime.getRuntime().exec("cmd.exe");
OutputStream outputStream = p.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream));
InputStream inputStream = p.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
writer.write("dir \n");
writer.flush();
Related
I'd like to automate a few tasks I am doing on multiple machines. I would like to use Ganymed's SSH2 library for this task. I am already capable of running multiple commands, getting the response from the server as well as a few other small things. The thing is that you can only execute one command per session which is why my execute method looks like the following in order to allow me to use one method for multiple commands:
public String execCmd(String cmd) throws IOException {
sess = conn.openSession();
sess.execCommand(cmd);
InputStream stdout = new StreamGobbler(sess.getStdout());
BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
String result = br.readLine();
br.close();
sess.close();
return (result);
}
The thing is that I seem unable to change my user using "su"+username. I read that the "su" command opens a new shell resulting in this issue.
Now - what would be the cleanest method to resolve this? I read about the possibility of opening a shell using this library but I fail to write to it and I seem unable to locate any examples for it.
Thanks in advance.
If you want to execute multiple commands. You have to request a pseudo terminal and start a shell afterwards. From the session object get the outstream to execute the commands.
...
sess.requrequestPTY();
sess.startShell();
Outstream outstream = sess.getStdin();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outstream));
final String cmd = new String(command);
bufferedWriter.write(cmd);
bufferedWriter.flush();
...
I'm trying to spawn a new console in java and get the ouput stream.
I tried this way :
Process p = Runtime.getRuntime().exec("cmd.exe /c start");
BufferedWriter out = new BufferedWriter( new OutputStreamWriter(
p.getOutputStream()));
the console spawn but i'm not able to write something on the stream !
The other way :
Process p = Runtime.getRuntime().exec("cmd.exe");
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
p.getOutputStream()));
This time i can write to the stream, but the console is not spawning !
I lack knowledge :/
Thank you in advance.
In your first way you started cmd and it started another process which you have no access too. Don't use this way if you need input/output stream.
The other way is right. Process is running fine. But you didn't provide any input for it. Obtain input stream and send some commands like "cd foo\n", "dir\n". As you can see this is regular stream so it requires to execute the command. Then you can use output stream too.
There are a lot of examples how to do so.
i want to open an external app using java.
Process p = Runtime.getRuntime().exec("/Users/kausar/myApp");
this runs the process as i can see in activity monitor.
Now the file i run is actually console app which then takes commands and gives response based on those commands.
for example if i go to terminal and put the same
Kausars-MacBook-Air:~ kausar$ /Users/kausar/myApp
myApp>
Now i can give commands to app as for example
myApp> SHOW 'Hi There'
These are commands taken as keyboard input in the console app, these are not parameters. I have seen different approaches with parameters. I tried the following as well but couldnt get it to work.
String res;
String cmnd = "SHOW \'Hi There\'";
OutputStream stdin = null;
InputStream stdout = null;
stdout = p.getInputStream();
stdin = p.getOutputStream();
stdin.write(cmnd.getBytes());
stdin.flush();
p.waitFor();
BufferedReader input = new BufferedReader(
new InputStreamReader(stdout));
while ((res = input.readLine()) != null) {
System.out.println(res)
}
input.close();
p.destroy();
Its displaying nothing while the same procedure with "/bin/bash -c ls" works just fine.
please help!
Of hand I would say the problem is with p.*wait*For()
Exactly what object and when to usee notify() or notifyAll() call to wake up the object thread would be something like on stdout and maybe a restructure of the process.
note: an interesting feature is the class field in BufferedReader called "lock", the api docs do mention some way of structuring your program so it can be notified.
I want to run an executable written in C++ and to see the cmd promt associated with it in foreground, since the executable prints some lines in the cmd.
I have written the following code, but all processes are created and run in background (In this code I open the dummy cmd.exe process, not my process).
Process p = new ProcessBuilder("C:\\Windows\\System32\\cmd.exe").start();
How can i enable foreground running of processes?
Thanks!
The issue is not whether the process is in the foreground or background. When you start a process using Java, you have to use Java to control that process' lifecyle. The Java API provides you access to various attributes of the process. What you're interested in here is the output of the process. That is represented by the process' InputStream. It seems counterintuitive, but it makes sense because from the perspective of your Java program, the process' output is the program's input. Conversely, if you need to send data to the process, you write to the process' OutputStream.
To sum up, access the process' InputStream and print that out to the command-line:
Process process = new ProcessBuilder("C:\\Path\\To\\My\\Application.exe").start();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
StringBuilder output = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
output.append(line);
}
System.out.println(line);
This code, of course, assumes that your process is not waiting for any input, i.e., it is not interactive.
Vivin Paliath's answer is really the way to go, then you can do whatever you want with the output, display it in your own dialogue, log it, interpret it, check for errors or whatever.
But just in case you really want that command window showing up. Execute cmd.exe and get the process' OutputStream and write the command (application.exe) to it ending with a new line.
Something along the lines of:
Process p = new ProcessBuilder("C:\\Windows\\System32\\cmd.exe").start();
out = p.getOutputStream();
out.write("path\\application.exe\r\n".getBytes());
out.flush();
Should usually drain the input stream too though anyway.
I'm trying to use Java to interface with a large batch file that uses psexec to execute commands on remote servers.
I'm able to launch the file using process builder and it works fine for most commands, but seems to be getting hung up.
One particular command from the batch file is as follows:
ECHO .
Echo Which would you like to reboot?
Echo 1-10. For computers, enter computer number.
Echo E. Exit
set /p userinp=choose a number(0-22):
but from Java I get:
.
Which would you like to reboot?
1-10. For computers, enter computer number.
E. Exit
and then it hangs
It's clearly not reading the set line, but more importantly I haven't yet figured out how to pass input back to the subprocess.
String[] command = {"cmd", "/c", "batchfile", "restart"};
ProcessBuilder builder = new ProcessBuilder(command);
builder.directory(new File("C:\\"));
Process process = builder.start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
Any input would be appreciated.
Your batch job requires that you actually provide input in order to proceed, which is why it appears to 'hang'. You need to supply this input to the process, via its output stream. A highly simplified example:
PrintWriter writer = new PrintWriter(process.getOutputStream());
writer.println("10");
writer.flush();
Your process doesn't hang, it is just waiting for some input at the command line, before to proceed.
As you are reading the output from the process via Process.getInputStream(), you can send input back to it using Process.getOutputStream().
public abstract OutputStream getOutputStream()
Gets the output stream of the subprocess. Output to the stream is piped into the standard input stream of the process represented by this Process object.
Implementation note: It is a good idea for the output stream to be buffered.
Returns:
the output stream connected to the normal input of the subprocess.