import java.io.*;
public class Clasa {
public static void main(String args[]) {
try {
Runtime rt = Runtime.getRuntime();
String comand = "net start MySQL55";
Process pr = rt.exec(" cmd.exe /C " + "net start MySQL55");
BufferedReader input = new BufferedReader(
new InputStreamReader(pr.getInputStream()));
String line = null;
while ((line = input.readLine()) != null) {
System.out.println(line);
}
int exitVal = pr.waitFor();
System.out.println("Exited with error code " + exitVal);
} catch (Exception e) {
System.out.println(e.toString());
e.printStackTrace();
}
}
}
I try this and gives me the next error code: Exited with error code 2
Related
I'm trying to run gcc via ProcessBuilder, but it says:
'gcc' is not recognized as an internal or external command,
operable program or batch file.
But running gcc via cmd works.
Here is code:
public static void main(String[] args) {
String command = "gcc C:\\Users\\pawel\\Desktop\\CFG-master\\test.c";
System.out.println(executeCommand(command));
}
public static String executeCommand(String command) {
String line;
String result = "";
try {
ProcessBuilder builder;
builder = new ProcessBuilder("cmd.exe", "/c", command);
builder.directory(new File("C:\\Users\\pawel"));
builder.redirectErrorStream(true);
Process p = builder.start();
BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
while (true) {
line = r.readLine();
if (line == null) {
break;
}
result += line + "\n";
}
} catch (IOException e) {
System.out.println("Exception = " + e.getMessage());
}
return result;
}
cmd screen
I would like the output of a shell command to go to a textArea in my java program as the shell command executes rather than after it has completed.
Current code that waits until process is complete and then shows the output:
ProcessBuilder builder = new ProcessBuilder("shell_command.sh");
builder.redirectErrorStream(true);
try {
Process p = builder.start();
String s;
BufferedReader stdout = new BufferedReader (
new InputStreamReader(p.getInputStream()));
while ((s = stdout.readLine()) != null) {
logPanel.addText(s + "\r\n"); // adds text to a textArea
}
System.out.println("Exit value: " + p.waitFor());
p.getInputStream().close();
p.getOutputStream().close();
p.getErrorStream().close();
} catch (Exception ex) {
ex.printStackTrace();
}
In UI thread...
(new Thread(new ShellCommand(logPanel) ) ).start();
New Class...
class ShellCommand implements Runnable {
LogPanel logPanel; // textArea
ShellCommand(LogPanel logPanel) {
this.logPanel = logPanel;
}
public void run() {
try {
ProcessBuilder builder = new ProcessBuilder("shell_command.sh");
builder.redirectErrorStream(true);
Process p = builder.start();
String s;
BufferedReader stdout = new BufferedReader(new
InputStreamReader(p.getInputStream()));
while ((s = stdout.readLine()) != null) {
logPanel.addText(s + "\r\n");
}
System.out.println("Exit value: " + p.waitFor());
p.getInputStream().close();
p.getOutputStream().close();
p.getErrorStream().close();
JOptionPane.showMessageDialog(null, "Done", "Message",
JOptionPane.INFORMATION_MESSAGE);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
I'm using the following script to execute commands and get output:
Runtime rt = Runtime.getRuntime();
static Runtime rt;
static Process proc;
public static void main(String[] Args) throws IOException, InterruptedException {
rt = Runtime.getRuntime();
String[] commands = {"ssh.exe","-o BatchMode=yes", "root#192.168.1.1", "cat /var/a.txt"};
// String[] commands = {"ssh.exe", "root#192.168.0.1"};
// String[] commands = { "ls", "-la" };
proc = rt.exec(commands);
new Thread("out") {
public void run() {
System.out.println("Thread: " + getName() + " running");
BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String s = null;
// read the output from the command
System.out.println("StdOut:\n");
try {
while ((s = stdInput.readLine()) != null) {
System.out.println("$ " + s);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
new Thread("err") {
public void run() {
System.out.println("Thread: " + getName() + " running");
BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
String s = null;
// read any errors from the attempted command
System.out.println("StdErr:\n");
try {
while ((s = stdError.readLine()) != null) {
System.out.println("! " + s);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
Thread.sleep(10000);
System.out.println("end");
}
If I execute "ls -la" or "ssh" I get the expected output. However, attempting to get a.txt content from remote device (line 1) fails and the operation hangs.
Executing "ssh root#192.168.0.1 cat a.txt" from command line works and retrieves the content.
Why is this happening? How can it be fixed?
Thanks
Because you need to read the two streams in separate threads, or merge them. You can't assume that the process will exit and therefore close its stderr before writing anything to stdtout, or rather without writing so little to stdout that it won't block.
import java.io.*;
public class ColorTest {
public static void main(String [] args){
try{
//Process p = Runtime.getRuntime().exec("cmd /c color 0a");
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = in.readline()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
I am not understanding why the command won't execute. The line that is commented is the one I need help with.
try {
try {
String[] command = {"cmd.exe", "/C", "Start", "D:\\test.bat"};
Runtime r = Runtime.getRuntime();
Process p = r.exec(command);
p.waitFor();
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(this, "Error" +"Execution!","Error",JOptionPane.ERROR_MESSAGE);
}
} catch (IOException ex) {
Logger.getLogger(DBBackUp.class.getName()).log(Level.SEVERE, null, ex);
}
When I run this code, I got only command promt. .bat file is not running.
How can I execute the batch file using this code?
Thank in Advance
Consider
using Apache Commons Exec.
let your "test.bat" be like this:
dir
pause
then you can execute this batch file as follows:
try
{
Runtime r = Runtime.getRuntime();
Process p = r.exec("rundll32 url.dll,FileProtocolHandler " + "D:\\test.bat");
p.waitFor();
}catch(Exception ex){ex.printStackTrace();}
You can try something like this:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class BatchExecuteService {
public static void main(String[] args) {
BatchExecuteService batchExecuteService = new BatchExecuteService();
batchExecuteService.run();
}
public void run() {
try {
String cmds[] = {"D:\\test.bat"};
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(cmds);
process.getOutputStream().close();
InputStream inputStream = process.getInputStream();
InputStreamReader inputstreamreader = new InputStreamReader(inputStream);
BufferedReader bufferedrReader = new BufferedReader(inputstreamreader);
String strLine = "";
while ((strLine = bufferedrReader.readLine()) != null) {
System.out.println(strLine);
}
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
}