I used the following code to execute simple OS command on Windows:
public class Ping {
public static void main(String[] args) throws IOException {
String command = "ping google.com";
Process process = Runtime.getRuntime().exec(command);
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
System.out.println();
System.out.println("Finished");
How to modify the code to insert multiple commands instead of one, so let us say I want to ping google.com, and then ping yahoo.com after that.
I tried to create array string like:
String [] command = {"ping google.com", "ping yahoo.com"};
However, this showed me an error.
I appreciate your help on this.
Use a loop:
String [] commands = {"ping google.com", "ping yahoo.com"};
for(String command: commands) {
Process process = Runtime.getRuntime().exec(command);
//more stuff
}
Related
While running below code prompt will open and it will show java version information. I want to print that java version information. please help me on this
public class Test {
public static void main(String[] args) throws IOException {
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("cmd.exe /c start cmd.exe /k \"java -version\"");
BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
// Read the output from the command
System.out.println("Here is the standard output of the command:\n");
String s = null;
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
}
}
At the moment you read the stream the process might not actualy be done yet. I'm pretty sure you first have to wait int exitVal = proc.waitFor(); on the process to finish before reading the outputStream.
for debugging wrapping part of this in a try with logging on the proc.getErrorStream() might help to
What i want to do is open a new cmd as the application starts and then write on it different commands in different moments.
Example: i start my application, it runs a new cmd that is hidden so it can't be seen, and then it writes "cd ..", the application wait ten seconds(for example) and then it writes "cd .." another time and finally it writes "dir" and it prints out the results of 'dir' command.
I've tryed to use this code to do that
public static void main(String[] args) throws IOException{
Runtime rt = Runtime.getRuntime();
Process process = rt.exec("cmd /c cd .. ");
process = rt.exec("cmd /c cd .. ");
process = rt.exec("cmd /c dir");
BufferedReader commReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = "";
while((line = commReader.readLine()) != null){
System.out.println(line);
}
}
but as i've seen it doesn't work because it runs command on different cmds.
So sorry for my terrible english and does anyone know how to solve that?
You are overwriting your process variable so of course it's going to execute multiple instances of cmd.
What you need to do is open a single process and then write commands to its OutputStream which is connected to the normal input of the sub-process.
public static void main(String[] args) throws IOException {
ProcessBuilder builder = new ProcessBuilder("cmd");
Process process = builder.start();
OutputStream stdin = process.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stdin));
writer.write("cd ..\n");
writer.write("dir\n");
writer.flush();
writer.close();
BufferedReader commReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = "";
while((line = commReader.readLine()) != null){
System.out.println(line);
}
}
How do I execute shell script file with an input parameter like "./flows.sh suspend" and print the the result to a file using java in linux?
This is a simple code to execute the shell script and read its output:
import java.io.*;
public class Test {
public static void main(String[] args) throws Exception {
String[] command = { "./flows.sh", "suspend" };
Process process = Runtime.getRuntime().exec(command);
BufferedReader reader = new BufferedReader(new InputStreamReader(
process.getInputStream()));
String s;
while ((s = reader.readLine()) != null) {
System.out.println("Script output: " + s); // Replace this line with the code to print the result to file
}
}
}
To print it to a file, just replace the System.out.println for the code to write into a file
You can use the JSCH API:
http://www.jcraft.com/jsch/examples/Shell.java.html
http://www.jcraft.com/jsch/examples/Exec.java.html
Bye!
I am using the following code to execute a command in java and getting the output:
String line;
try {
System.out.println(command);
Process p = Runtime.getRuntime().exec(command);
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
print(line);
}
input.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
However, apparently the command 'tree' and 'assoc' and others aren't actually their own programs that can be run through Java, rather they are coded in as parts of command prompt, so I cannot get the output. Is there actually any way to do this? Thank you
I don't have a windows machine to test this on, but generally to get the output for those builtins you run cmd.exe as the program and pass it the command as an argument.
Now, this has some limitations, because when the command finishes the executable stops. So if you do a cd command, it will work, but it only affect the subprocess, not your process. For those sorts of things, if you want them to change the state of your process, you'll need to use other facilities.
This version works on a Mac:
import java.io.*;
public class cmd {
public static void
main(String[] argv){
String line;
String[] cmd = {"bash","-c","ls"};
System.out.println("Hello, world!\n");
try {
Process p = Runtime.getRuntime().exec(cmd);
BufferedReader input =
new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
System.out.println(line);
}
input.close();
} catch (Exception e) {
}
return ;
}
}
How do I run multiple commands in SSH using Java runtime?
the command: ssh user#127.0.0.1 'export MYVAR=this/dir/is/cool; /run/my/script
/myscript; echo $MYVAR'
#Test
public void testSSHcmd() throws Exception
{
StringBuilder cmd = new StringBuilder();
cmd.append("ssh ");
cmd.append("user#127.0.0.1 ");
cmd.append("'export ");
cmd.append("MYVAR=this/dir/is/cool; ");
cmd.append("/run/my/script/myScript; ");
cmd.append("echo $MYVAR'");
Process p = Runtime.getRuntime().exec(cmd.toString());
}
The command by its self will work but when trying to execute from java run-time it does not. Any suggestions or advice?
Use the newer ProcessBuilder class instead of Runtime.exec. You can construct one by specifying the program and its list of arguments as shown in my code below. You don't need to use single-quotes around the command. You should also read the stdout and stderr streams and waitFor for the process to finish.
ProcessBuilder pb = new ProcessBuilder("ssh",
"user#127.0.0.1",
"export MYVAR=this/dir/is/cool; /run/my/script/myScript; echo $MYVAR");
pb.redirectErrorStream(); //redirect stderr to stdout
Process process = pb.start();
InputStream inputStream = process.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line = null;
while((line = reader.readLine())!= null) {
System.out.println(line);
}
process.waitFor();
If the Process just hangs I suspect that /run/my/script/myScript outputs something to stderr. You need to handle that output aswell as stdout:
public static void main(String[] args) throws Exception {
String[] cmd = {"ssh", "root#localhost", "'ls asd; ls'" };
final Process p = Runtime.getRuntime().exec(cmd);
// ignore all errors (print to std err)
new Thread() {
#Override
public void run() {
try {
BufferedReader err = new BufferedReader(
new InputStreamReader(p.getErrorStream()));
String in;
while((in = err.readLine()) != null)
System.err.println(in);
err.close();
} catch (IOException e) {}
}
}.start();
// handle std out
InputStreamReader isr = new InputStreamReader(p.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder ret = new StringBuilder();
char[] data = new char[1024];
int read;
while ((read = reader.read(data)) != -1)
ret.append(data, 0, read);
reader.close();
// wait for the exit code
int exitCode = p.waitFor();
}
The veriant of Runtime.exec you are calling splits the command string into several tokens which are then passed to ssh. What you need is one of the variants where you can provide a string array. Put the complete remote part into one argument while stripping the outer quotes. Example
Runtime.exec(new String[]{
"ssh",
"user#127.0.0.1",
"export MYVAR=this/dir/is/cool; /run/my/script/myScript; echo $MYVAR"
});
That's it.
You might want to take a look at the JSch library. It allows you to do all sorts of SSH things with remote hosts including executing commands and scripts.
They have examples listed here: http://www.jcraft.com/jsch/examples/
Here is the right way to do it:
Runtime rt=Runtime.getRuntime();
rt.exec("cmd.exe /c start <full path>");
For example:
Runtime rt=Runtime.getRuntime();
rt.exec("cmd.exe /c start C:/aa.txt");
If you are using SSHJ from https://github.com/shikhar/sshj/
public static void main(String[] args) throws IOException {
final SSHClient ssh = new SSHClient();
ssh.loadKnownHosts();
ssh.connect("10.x.x.x");
try {
//ssh.authPublickey(System.getProperty("root"));
ssh.authPassword("user", "xxxx");
final Session session = ssh.startSession();
try {
final Command cmd = session.exec("cd /backup; ls; ./backup.sh");
System.out.println(IOUtils.readFully(cmd.getInputStream()).toString());
cmd.join(5, TimeUnit.SECONDS);
System.out.println("\n** exit status: " + cmd.getExitStatus());
} finally {
session.close();
}
} finally {
ssh.disconnect();
}
}