How do I execute a sequence of related console commands? - java

I'm currently working on a project where a client receives shell/console commands from a server, and must execute them.
How do I get Java to run these commands from within either a shell or a command prompt? I'm hoping to be able to disregard the platform type - and not have to specify shell or command prompt - but if I can't, then that's okay.
I must be able to send a sequence of related commands, not just one command. This means that the shell/prompt cannot exit or close between commands.
My current code, as follows, allows for the execution of a sequence of programs, but these commands must somehow be piped into a shell/command prompt, from which the output must be read.
ArrayList<String> comDat = new ArrayList<>();
while(true) {
String input = con.recv();
System.out.println("> " + input);
if(!input.equals("EOF")) comDat.add(input); else {
String[] s = new String[comDat.size()];
for(int i = 0; i < comDat.size(); i++) s[i] = comDat.get(i);
System.out.println("---Command sequence executing---");
Process p = Runtime.getRuntime().exec(s);
p.waitFor();
System.out.println("---ErrorStream output---"); String line = "";
BufferedReader errStream = new BufferedReader(new InputStreamReader(p.getErrorStream()));
while((line = errStream.readLine()) != null) System.out.println("< " + line);
System.out.println("\n---OutputStream output---"); line = "";
BufferedReader outStream = new BufferedReader(new InputStreamReader(p.getInputStream()));
while((line = errStream.readLine()) != null) System.out.println("< " + line);
}
Thread.sleep(200);
}
Thanks for the help!

The basic premise revoles around the fact the dir isn't an external command but is function of cmd.
I would avoid BufferedReaders when reading the output of a process as not all processes use new lines when sending output (such as progress indicators), instead you should read char for char (IMHO).
You should us ProcessBuilder instead of Runtime#exec. It provides better management and allows you to redirect the error stream into the input stream, making it easier to read the input.
import java.io.IOException;
import java.io.InputStream;
public class TestProcessBuilder {
public static void main(String[] args) {
try {
ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "dir");
pb.redirectError();
Process p = pb.start();
InputStreamConsumer isc = new InputStreamConsumer(p.getInputStream());
isc.start();
int exitCode = p.waitFor();
isc.join();
System.out.println("Process terminated with " + exitCode);
} catch (IOException | InterruptedException exp) {
exp.printStackTrace();
}
}
public static class InputStreamConsumer extends Thread {
private InputStream is;
public InputStreamConsumer(InputStream is) {
this.is = is;
}
#Override
public void run() {
try {
int value = -1;
while ((value = is.read()) != -1) {
System.out.print((char)value);
}
} catch (IOException exp) {
exp.printStackTrace();
}
}
}
}

Related

Is it possible to execute java -jar programmatically? [duplicate]

I found several code snippets for running cmd commands through a Java class, but I wasn't able to understand it.
This is code for opening the cmd
public void excCommand(String new_dir){
Runtime rt = Runtime.getRuntime();
try {
rt.exec(new String[]{"cmd.exe","/c","start"});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
And I found some other links for adding other commands such as cd
http://www.coderanch.com/t/109753/Linux-UNIX/exec-command-cd-command-java
How to open the command prompt and insert commands using Java?
Can anyone help me to understand how to cd a directory such as:
cd C:\Program Files\Flowella
then run other commands on that directory?
One way to run a process from a different directory to the working directory of your Java program is to change directory and then run the process in the same command line. You can do this by getting cmd.exe to run a command line such as cd some_directory && some_program.
The following example changes to a different directory and runs dir from there. Admittedly, I could just dir that directory without needing to cd to it, but this is only an example:
import java.io.*;
public class CmdTest {
public static void main(String[] args) throws Exception {
ProcessBuilder builder = new ProcessBuilder(
"cmd.exe", "/c", "cd \"C:\\Program Files\\Microsoft SQL Server\" && dir");
builder.redirectErrorStream(true);
Process p = builder.start();
BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while (true) {
line = r.readLine();
if (line == null) { break; }
System.out.println(line);
}
}
}
Note also that I'm using a ProcessBuilder to run the command. Amongst other things, this allows me to redirect the process's standard error into its standard output, by calling redirectErrorStream(true). Doing so gives me only one stream to read from.
This gives me the following output on my machine:
C:\Users\Luke\StackOverflow>java CmdTest
Volume in drive C is Windows7
Volume Serial Number is D8F0-C934
Directory of C:\Program Files\Microsoft SQL Server
29/07/2011 11:03 <DIR> .
29/07/2011 11:03 <DIR> ..
21/01/2011 20:37 <DIR> 100
21/01/2011 20:35 <DIR> 80
21/01/2011 20:35 <DIR> 90
21/01/2011 20:39 <DIR> MSSQL10_50.SQLEXPRESS
0 File(s) 0 bytes
6 Dir(s) 209,496,424,448 bytes free
You can try this:-
Process p = Runtime.getRuntime().exec(command);
If you want to perform actions like cd, then use:
String[] command = {command_to_be_executed, arg1, arg2};
ProcessBuilder builder = new ProcessBuilder(command);
builder = builder.directory(new File("directory_location"));
Example:
String[] command = {"ls", "-al"};
ProcessBuilder builder = new ProcessBuilder(command);
builder = builder.directory(new File("/ngs/app/abc"));
Process p = builder.start();
It is important that you split the command and all arguments in separate strings of the string array (otherwise they will not be provided correctly by the ProcessBuilder API).
Here is a more complete implementation of command line execution.
Usage
executeCommand("ls");
Output:
12/27/2017 11:18:11:732: ls
12/27/2017 11:18:11:820: build.gradle
12/27/2017 11:18:11:820: gradle
12/27/2017 11:18:11:820: gradlew
12/27/2017 11:18:11:820: gradlew.bat
12/27/2017 11:18:11:820: out
12/27/2017 11:18:11:820: settings.gradle
12/27/2017 11:18:11:820: src
Code
private void executeCommand(String command) {
try {
log(command);
Process process = Runtime.getRuntime().exec(command);
logOutput(process.getInputStream(), "");
logOutput(process.getErrorStream(), "Error: ");
process.waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
private void logOutput(InputStream inputStream, String prefix) {
new Thread(() -> {
Scanner scanner = new Scanner(inputStream, "UTF-8");
while (scanner.hasNextLine()) {
synchronized (this) {
log(prefix + scanner.nextLine());
}
}
scanner.close();
}).start();
}
private static SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss:SSS");
private synchronized void log(String message) {
System.out.println(format.format(new Date()) + ": " + message);
}
My example (from real project)
folder — File.
zipFile, filesString — String;
final String command = "/bin/tar -xvf " + zipFile + " " + filesString;
logger.info("Start unzipping: {} into the folder {}", command, folder.getPath());
final Runtime r = Runtime.getRuntime();
final Process p = r.exec(command, null, folder);
final int returnCode = p.waitFor();
if (logger.isWarnEnabled()) {
final BufferedReader is = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = is.readLine()) != null) {
logger.warn(line);
}
final BufferedReader is2 = new BufferedReader(new InputStreamReader(p.getErrorStream()));
while ((line = is2.readLine()) != null) {
logger.warn(line);
}
}
The easiest way would be to use Runtime.getRuntime.exec().
For example, to get a registry value for the default browser on Windows:
String command = "REG QUERY HKEY_CLASSES_ROOT\\http\\shell\\open\\command";
try
{
Process process = Runtime.getRuntime().exec(command);
} catch (IOException e)
{
e.printStackTrace();
}
Then use a Scanner to get the output of the command, if necessary.
Scanner kb = new Scanner(process.getInputStream());
Note: the \ is an escape character in a String, and must be escaped to work properly (hence the \\).
However, there is no executable called cd, because it can't be implemented in a separate process.
The one case where the current working directory matters is executing an external process (using ProcessBuilder or Runtime.exec()). In those cases you can specify the working directory to use for the newly started process explicitly.
Easiest way for your command:
System.setProperty("user.dir", "C:\\Program Files\\Flowella");
Try this:
Process runtime = Runtime.getRuntime().exec("cmd /c start notepad++.exe");
Once you get the reference to Process, you can call getOutpuStream on it to get the standard input of the cmd prompt. Then you can send any command over the stream using write method as with any other stream.
Note that it is process.getOutputStream() which is connected to the stdin on the spawned process. Similarly, to get the output of any command, you will need to call getInputStream and then read over this as any other input stream.
Stopping and Disabling a service can be done via below code:
static void sdService() {
String[] cmd = {"cmd.exe", "/c", "net", "stop", "MSSQLSERVER"};
try {
Process process = new ProcessBuilder(cmd).start();
process.waitFor();
String line = null;
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
line = null;
bufferedReader = null;
Process p = Runtime.getRuntime().exec("sc config MSSQLSERVER start= disabled");
p.waitFor();
bufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
Enabling and Starting a service can be done via below code
static void esService() {
String[] cmd = {"cmd.exe", "/c", "net", "start", "MSSQLSERVER"};
try {
Process p = Runtime.getRuntime().exec("sc config MSSQLSERVER start= auto");
//Process p = Runtime.getRuntime().exec("sc config MSSQLSERVER start= demand");
p.waitFor();
String line = null;
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
line = null;
bufferedReader = null;
Process process = new ProcessBuilder(cmd).start();
process.waitFor();
bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
Executing command from any folder can be done via below code.
static void runFromSpecificFolder() {
try {
ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe", "/c", "cd \"C:\\Users\\himan\\Desktop\\Java_Test_Deployment\\jarfiles\" && dir");
//processBuilder.directory(new File("C://Users//himan//Desktop//Java_Test_Deployment//jarfiles"));
processBuilder.redirectErrorStream(true);
Process p = processBuilder.start();
p.waitFor();
String line = null;
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
sdService();
runFromSpecificFolder();
esService();
}
You can't run cd this way, because cd isn't a real program; it's a built-in part of the command-line, and all it does is change the command-line's environment. It doesn't make sense to run it in a subprocess, because then you're changing that subprocess's environment — but that subprocess closes immediately, discarding its environment.
To set the current working directory in your actual Java program, you should write:
System.setProperty("user.dir", "C:\\Program Files\\Flowella");
public class Demo {
public static void main(String args[]) throws IOException {
Process process = Runtime.getRuntime().exec("/Users/******/Library/Android/sdk/platform-tools/adb" + " shell dumpsys battery ");
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
while (true) {
line = in.readLine();
if (line == null) { break; }
System.out.println(line);
}
}
}
The simplest and shortest way is to use CmdTool library.
new Cmd()
.configuring(new WorkDir("C:/Program Files/Flowella"))
.command("cmd.exe", "/c", "start")
.execute();
You can find more examples here.
one of the way to execute cmd from java !
public void executeCmd() {
String anyCommand="your command";
try {
Process process = Runtime.getRuntime().exec("cmd /c start cmd.exe /K " + anyCommand);
} catch (IOException e) {
e.printStackTrace();
}
}
Here the value adder is use of ampersands to batch commands and correct format for change drive with cd.
public class CmdCommander {
public static void main(String[] args) throws Exception {
//easyway to start native windows command prompt from Intellij
/*
Rules are:
1.baseStart must be dual start
2.first command must not have &.
3.subsequent commands must be prepended with &
4.drive change needs extra &
5.use quotes at start and end of command batch
*/
String startQuote = "\"";
String endQuote = "\"";
//String baseStart_not_taking_commands = " cmd /K start ";
String baseStart = " cmd /K start cmd /K ";//dual start is must
String first_command_chcp = " chcp 1251 ";
String dirList = " &dir ";//& in front of commands after first command means enter
//change drive....to yours
String changeDir = " &cd &I: ";//extra & makes changing drive happen
String javaLaunch = " &java ";//just another command
String javaClass = " Encodes ";//parameter for java needs no &
String javaCommand = javaLaunch + javaClass;
//build batch command
String totalCommand =
baseStart +
startQuote +
first_command_chcp +
//javaCommand +
changeDir +
dirList +
endQuote;
System.out.println(totalCommand);//prints into Intellij terminal
runCmd(totalCommand);
//Thread t = Thread.currentThread();
//t.sleep(3000);
System.out.println("loppu hep");//prints into Intellij terminal
}
public static void runCmd(String command) throws Exception {
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(command);
}
}

How to get a direct output from a running process?

I've been trying to read lines of console output from a command in realtime, but I've only been able to get it after the process has ended. How could I run a command and get the output as it runs?
Here's the code I'm currently using
public OutputStream executeCommand(String command) {
try {
ProcessBuilder pb = new ProcessBuilder(command);
Process p = pb.start();
OutputStream ops = p.getOutputStream();
return ops;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
Be aware that the code below can throw an IOException.
Runtime runtime = Runtime.getRuntime() ;
Process process = runtime.exec("Your command") ;
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())) ;
String line = null ;
while ((line = reader.readLine())!= null){
System.out.println(line);
}

Getting output from executing a terminal command in a java code running inside Cubieboard Platform

The code that I am using for running a terminal command in Linux Debian and getting the output inside a java program is this:
public static String execute(String command) {
StringBuilder sb = new StringBuilder();
String[] commands = new String[]{"/bin/sh", "-c", command};
try {
Process proc = new ProcessBuilder(commands).start();
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(proc.getErrorStream()));
String s = null;
while ((s = stdInput.readLine()) != null) {
sb.append(s);
sb.append("\n");
}
while ((s = stdError.readLine()) != null) {
sb.append(s);
sb.append("\n");
}
} catch (IOException e) {
return e.getMessage();
}
return sb.toString();
}
Now the problem is, it works for normal commands like ls / and gives back the appropriate result. But my goal is to run commands like:
echo 23 > /sys/class/gpio/export
which is, for example, for activating the gpio pin in the CubieBoard platform.
(Cubieboard is a mini-pc board like Raspberry Pi).
Now running this command in the terminal of the system itself, works fine and gives me the proper result. But when i am running it from this java code, i cannot get any results back.
The point is that, it works and the command executes well, but just that i cannot get the output message of the command!
For example if the pin was active from the past, then normally it should give me back the result like:
bash: echo: write error: Device or resource busy
But when i run this command through java code above, i do not get any response back.
(again it takes effect but just the response of the terminal i cannot get!)
When i run the code, both stdInput and stdError variables in the code are having the value null. :(
Please help me so that i can finish my project. this is the only part that is remaining :(
Thank you.
There maybe the childProcess doesn't run to end
Please to try:
proc.waitFor()
and run read stdInput and stdError in other Thread before proc.waitFor().
Example:
public static String execute(String command) {
String[] commands = new String[] { "/bin/sh", "-c", command };
ExecutorService executor = Executors.newCachedThreadPool();
try {
ProcessBuilder builder = new ProcessBuilder(commands);
/*-
Process proc = builder.start();
CollectOutput collectStdOut = new CollectOutput(
proc.getInputStream());
executor.execute(collectStdOut);
CollectOutput collectStdErr = new CollectOutput(
proc.getErrorStream());
executor.execute(collectStdErr);
// */
// /*-
// merges standard error and standard output
builder.redirectErrorStream();
Process proc = builder.start();
CollectOutput out = new CollectOutput(proc.getInputStream());
executor.execute(out);
// */
// child proc exit code
int waitFor = proc.waitFor();
return out.get();
} catch (IOException e) {
return e.getMessage();
} catch (InterruptedException e) {
// proc maybe interrupted
e.printStackTrace();
}
return null;
}
public static class CollectOutput implements Runnable {
private final StringBuffer buffer = new StringBuffer();
private final InputStream inputStream;
public CollectOutput(InputStream inputStream) {
super();
this.inputStream = inputStream;
}
/*
* (non-Javadoc)
*
* #see java.lang.Runnable#run()
*/
#Override
public void run() {
BufferedReader reader = null;
String line;
try {
reader = new BufferedReader(new InputStreamReader(inputStream));
while ((line = reader.readLine()) != null) {
buffer.append(line).append('\n');
}
} catch (Exception e) {
System.err.println(e);
} finally {
try {
reader.close();
} catch (IOException e) {
}
}
}
public String get() {
return buffer.toString();
}
}
the code is right, just in the second line, I changed
"/bin/sh" to "/bin/bash"
And everything works!
sh == bash?
For a long time, /bin/sh used to point to /bin/bash on most GNU/Linux systems. As a result, it had almost become safe to ignore the difference between the two. But that started to change recently.
Some popular examples of systems where /bin/sh does not point to /bin/bash (and on some of which /bin/bash may not even exist) are:
Modern Debian and Ubuntu systems, which symlink sh to dash by default;
Busybox, which is usually run during the Linux system boot time as part of initramfs. It uses the ash shell implementation.
BSDs. OpenBSD uses pdksh, a descendant of the Korn shell. FreeBSD's sh is a descendant of the original UNIX Bourne shell.
For more information on this please refer to :
Difference between sh and bash

Run cmd commands through Java

I found several code snippets for running cmd commands through a Java class, but I wasn't able to understand it.
This is code for opening the cmd
public void excCommand(String new_dir){
Runtime rt = Runtime.getRuntime();
try {
rt.exec(new String[]{"cmd.exe","/c","start"});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
And I found some other links for adding other commands such as cd
http://www.coderanch.com/t/109753/Linux-UNIX/exec-command-cd-command-java
How to open the command prompt and insert commands using Java?
Can anyone help me to understand how to cd a directory such as:
cd C:\Program Files\Flowella
then run other commands on that directory?
One way to run a process from a different directory to the working directory of your Java program is to change directory and then run the process in the same command line. You can do this by getting cmd.exe to run a command line such as cd some_directory && some_program.
The following example changes to a different directory and runs dir from there. Admittedly, I could just dir that directory without needing to cd to it, but this is only an example:
import java.io.*;
public class CmdTest {
public static void main(String[] args) throws Exception {
ProcessBuilder builder = new ProcessBuilder(
"cmd.exe", "/c", "cd \"C:\\Program Files\\Microsoft SQL Server\" && dir");
builder.redirectErrorStream(true);
Process p = builder.start();
BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while (true) {
line = r.readLine();
if (line == null) { break; }
System.out.println(line);
}
}
}
Note also that I'm using a ProcessBuilder to run the command. Amongst other things, this allows me to redirect the process's standard error into its standard output, by calling redirectErrorStream(true). Doing so gives me only one stream to read from.
This gives me the following output on my machine:
C:\Users\Luke\StackOverflow>java CmdTest
Volume in drive C is Windows7
Volume Serial Number is D8F0-C934
Directory of C:\Program Files\Microsoft SQL Server
29/07/2011 11:03 <DIR> .
29/07/2011 11:03 <DIR> ..
21/01/2011 20:37 <DIR> 100
21/01/2011 20:35 <DIR> 80
21/01/2011 20:35 <DIR> 90
21/01/2011 20:39 <DIR> MSSQL10_50.SQLEXPRESS
0 File(s) 0 bytes
6 Dir(s) 209,496,424,448 bytes free
You can try this:-
Process p = Runtime.getRuntime().exec(command);
If you want to perform actions like cd, then use:
String[] command = {command_to_be_executed, arg1, arg2};
ProcessBuilder builder = new ProcessBuilder(command);
builder = builder.directory(new File("directory_location"));
Example:
String[] command = {"ls", "-al"};
ProcessBuilder builder = new ProcessBuilder(command);
builder = builder.directory(new File("/ngs/app/abc"));
Process p = builder.start();
It is important that you split the command and all arguments in separate strings of the string array (otherwise they will not be provided correctly by the ProcessBuilder API).
Here is a more complete implementation of command line execution.
Usage
executeCommand("ls");
Output:
12/27/2017 11:18:11:732: ls
12/27/2017 11:18:11:820: build.gradle
12/27/2017 11:18:11:820: gradle
12/27/2017 11:18:11:820: gradlew
12/27/2017 11:18:11:820: gradlew.bat
12/27/2017 11:18:11:820: out
12/27/2017 11:18:11:820: settings.gradle
12/27/2017 11:18:11:820: src
Code
private void executeCommand(String command) {
try {
log(command);
Process process = Runtime.getRuntime().exec(command);
logOutput(process.getInputStream(), "");
logOutput(process.getErrorStream(), "Error: ");
process.waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
private void logOutput(InputStream inputStream, String prefix) {
new Thread(() -> {
Scanner scanner = new Scanner(inputStream, "UTF-8");
while (scanner.hasNextLine()) {
synchronized (this) {
log(prefix + scanner.nextLine());
}
}
scanner.close();
}).start();
}
private static SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss:SSS");
private synchronized void log(String message) {
System.out.println(format.format(new Date()) + ": " + message);
}
My example (from real project)
folder — File.
zipFile, filesString — String;
final String command = "/bin/tar -xvf " + zipFile + " " + filesString;
logger.info("Start unzipping: {} into the folder {}", command, folder.getPath());
final Runtime r = Runtime.getRuntime();
final Process p = r.exec(command, null, folder);
final int returnCode = p.waitFor();
if (logger.isWarnEnabled()) {
final BufferedReader is = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = is.readLine()) != null) {
logger.warn(line);
}
final BufferedReader is2 = new BufferedReader(new InputStreamReader(p.getErrorStream()));
while ((line = is2.readLine()) != null) {
logger.warn(line);
}
}
The easiest way would be to use Runtime.getRuntime.exec().
For example, to get a registry value for the default browser on Windows:
String command = "REG QUERY HKEY_CLASSES_ROOT\\http\\shell\\open\\command";
try
{
Process process = Runtime.getRuntime().exec(command);
} catch (IOException e)
{
e.printStackTrace();
}
Then use a Scanner to get the output of the command, if necessary.
Scanner kb = new Scanner(process.getInputStream());
Note: the \ is an escape character in a String, and must be escaped to work properly (hence the \\).
However, there is no executable called cd, because it can't be implemented in a separate process.
The one case where the current working directory matters is executing an external process (using ProcessBuilder or Runtime.exec()). In those cases you can specify the working directory to use for the newly started process explicitly.
Easiest way for your command:
System.setProperty("user.dir", "C:\\Program Files\\Flowella");
Try this:
Process runtime = Runtime.getRuntime().exec("cmd /c start notepad++.exe");
Once you get the reference to Process, you can call getOutpuStream on it to get the standard input of the cmd prompt. Then you can send any command over the stream using write method as with any other stream.
Note that it is process.getOutputStream() which is connected to the stdin on the spawned process. Similarly, to get the output of any command, you will need to call getInputStream and then read over this as any other input stream.
Stopping and Disabling a service can be done via below code:
static void sdService() {
String[] cmd = {"cmd.exe", "/c", "net", "stop", "MSSQLSERVER"};
try {
Process process = new ProcessBuilder(cmd).start();
process.waitFor();
String line = null;
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
line = null;
bufferedReader = null;
Process p = Runtime.getRuntime().exec("sc config MSSQLSERVER start= disabled");
p.waitFor();
bufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
Enabling and Starting a service can be done via below code
static void esService() {
String[] cmd = {"cmd.exe", "/c", "net", "start", "MSSQLSERVER"};
try {
Process p = Runtime.getRuntime().exec("sc config MSSQLSERVER start= auto");
//Process p = Runtime.getRuntime().exec("sc config MSSQLSERVER start= demand");
p.waitFor();
String line = null;
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
line = null;
bufferedReader = null;
Process process = new ProcessBuilder(cmd).start();
process.waitFor();
bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
Executing command from any folder can be done via below code.
static void runFromSpecificFolder() {
try {
ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe", "/c", "cd \"C:\\Users\\himan\\Desktop\\Java_Test_Deployment\\jarfiles\" && dir");
//processBuilder.directory(new File("C://Users//himan//Desktop//Java_Test_Deployment//jarfiles"));
processBuilder.redirectErrorStream(true);
Process p = processBuilder.start();
p.waitFor();
String line = null;
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
sdService();
runFromSpecificFolder();
esService();
}
You can't run cd this way, because cd isn't a real program; it's a built-in part of the command-line, and all it does is change the command-line's environment. It doesn't make sense to run it in a subprocess, because then you're changing that subprocess's environment — but that subprocess closes immediately, discarding its environment.
To set the current working directory in your actual Java program, you should write:
System.setProperty("user.dir", "C:\\Program Files\\Flowella");
public class Demo {
public static void main(String args[]) throws IOException {
Process process = Runtime.getRuntime().exec("/Users/******/Library/Android/sdk/platform-tools/adb" + " shell dumpsys battery ");
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
while (true) {
line = in.readLine();
if (line == null) { break; }
System.out.println(line);
}
}
}
The simplest and shortest way is to use CmdTool library.
new Cmd()
.configuring(new WorkDir("C:/Program Files/Flowella"))
.command("cmd.exe", "/c", "start")
.execute();
You can find more examples here.
one of the way to execute cmd from java !
public void executeCmd() {
String anyCommand="your command";
try {
Process process = Runtime.getRuntime().exec("cmd /c start cmd.exe /K " + anyCommand);
} catch (IOException e) {
e.printStackTrace();
}
}
Here the value adder is use of ampersands to batch commands and correct format for change drive with cd.
public class CmdCommander {
public static void main(String[] args) throws Exception {
//easyway to start native windows command prompt from Intellij
/*
Rules are:
1.baseStart must be dual start
2.first command must not have &.
3.subsequent commands must be prepended with &
4.drive change needs extra &
5.use quotes at start and end of command batch
*/
String startQuote = "\"";
String endQuote = "\"";
//String baseStart_not_taking_commands = " cmd /K start ";
String baseStart = " cmd /K start cmd /K ";//dual start is must
String first_command_chcp = " chcp 1251 ";
String dirList = " &dir ";//& in front of commands after first command means enter
//change drive....to yours
String changeDir = " &cd &I: ";//extra & makes changing drive happen
String javaLaunch = " &java ";//just another command
String javaClass = " Encodes ";//parameter for java needs no &
String javaCommand = javaLaunch + javaClass;
//build batch command
String totalCommand =
baseStart +
startQuote +
first_command_chcp +
//javaCommand +
changeDir +
dirList +
endQuote;
System.out.println(totalCommand);//prints into Intellij terminal
runCmd(totalCommand);
//Thread t = Thread.currentThread();
//t.sleep(3000);
System.out.println("loppu hep");//prints into Intellij terminal
}
public static void runCmd(String command) throws Exception {
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(command);
}
}

How do I run multiple commands in SSH through Java?

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();
}
}

Categories