I need to build a java program to reset network in windows 10, this command needs cmd to be opened as administrator I tried to build it, but it gives me this error
Cannot run program "runas /profile /user:Administrator "cmd.exe /c Powrprof.dll,SetSuspendState"": CreateProcess error=2, The system cannot find the file specified
this is my code
try {
String[] command
= {
"runas /profile /user:Administrator \"cmd.exe /c Powrprof.dll,SetSuspendState\"",};
Process p = Runtime.getRuntime().exec(command);
new Thread(new SyncPipe(p.getErrorStream(), System.err)).start();
new Thread(new SyncPipe(p.getInputStream(), System.out)).start();
PrintWriter stdin = new PrintWriter(p.getOutputStream());
stdin.println("netsh winsock reset");
stdin.close();
int returnCode = p.waitFor();
System.out.println("Return code = " + returnCode);
stat_lbl.setText("Network reset Successfully");
} catch (IOException | InterruptedException e) {
System.out.println(e.getMessage());
}
I don't understand what the problem is and how can I resolve it
You're giving the command as an array with a single element, which is treated as a single command. You're already giving the command as an array - split it accordingly, where runas is the command, and everything else is an argument to runas:
String[] command = {
"runas",
"/profile",
"/user:Administrator",
"cmd.exe /c Powrprof.dll,SetSuspendState",
};
Note that you don't have to add quotes to the last argument.
You can make your program a bit better by using ProcessBuilder. Now you're redirecting streams yourself, but you can easily let ProcessBuilder handle that for you:
Process p = new ProcessBuilder(command).inheritIO().start();
PrintWriter stdin = new PrintWriter(p.getOutputStream());
stdin.println("netsh winsock reset");
stdin.close();
int returnCode = p.waitFor();
System.out.println("Return code = " + returnCode);
Related
I have following java code
public static void main(String a[]) {
String location = "C:\\Users\\test\\output\\testProject";
File dir = new File("C:\\Users\\test\\cmds");
ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/C", "Start /wait","packageProject.bat",location);
pb.directory(dir);
Process p = null;
try {
p = pb.start();
p.waitFor();
}
catch (IOException e) {
e.printStackTrace();
}
catch(InterruptedException e) {
e.printStackTrace();
}
System.out.println("Folder created");
}
Batch file is
cd "C:\Users\test\output\test-master"
mvn clean install -DskipTests
exit
It is packaging file but not command prompt is not closing once process is complete.
Please suggest.
You should remove wrapper CMD.EXE and start, just call the batch file directly as:
String bat = new File(dir, "packageProject.bat").getAbsolutePath();
ProcessBuilder pb = new ProcessBuilder(bat , location);
pb.directory(dir);
Process p = pb.start();
p.waitFor();
If this process generates a lot of output you may run into a second problem if you don't consume error and output streams. You can do this in background threads, or simply send stdout/err to files by adding these calls before pb.start():
pb.redirectOutput(new File(location, "std.out"));
pb.redirectError(new File(location, "std.err"));
I am trying to run a simple "cecopy" in java. I call "cmd.exe" and pass the command through. It creates the directories but doesnt carry out the copy.
Below is the command I am using, set as a string in java:
String cmd = "mkdir \"C:\\\\Dominos\\\\DATFiles\" >> log.txt\n"
+ "\n" +
"cecopy \"dev:\\Application\\\\MCL\\\\Projects\\\\Default\\\\aa.dat\" \"C:\\\\Dominos\\\\DATFiles\");
Below is how I am calling command prompt to execute the DOS statement:
Runtime rt = Runtime.getRuntime();
try {
Process p = rt.exec("cmd.exe /c" + cmd); // Call CMD
p.waitFor(); // Wait till CMD finishes
} catch (InterruptedException | IOException ex) {
Logger.getLogger(readData.class.getName()).log(Level.SEVERE, null, ex);
}
Any help?
Thanks in advance!
You can use process builder. It handles commands with arguments neatly.
ProcessBuilder processBuilder = new ProcessBuilder();
p.command("cmd_to_run", "args_if_any");
p.start();
I've been trying to run an executable .bat file in Java using the line:
Runtime.getRuntime().exec("call " + batFile);
But it returns an error
Could not start process with commandLine nullCreateProcess: call batfilename here error=2
IOException: Create Process: call batfilename here error=2
I managed to bypass this by replacing the String in the exec() function with "cmd /c start " + batFile but this opens a command prompt which is not allowed.
Are there workarounds to this? Thanks!
Try running the batch file directly, for example...
ProcessBuilder pb = new ProcessBuilder("C:/Test.bat");
pb.redirectError();
try {
Process p = pb.start();
try (InputStream inputStream = p.getInputStream()) {
int in = -1;
while ((in = inputStream.read()) != -1) {
System.out.print((char)in);
}
}
System.out.println("Exited with " + p.waitFor());
} catch (IOException | InterruptedException ex) {
ex.printStackTrace();
}
This was the batch file...
#echo Hello World
(I know, massive) and the code outputted...
Hello World
Exited with 0
A little late but for others who want to try I found the /B of start command.
String[] command = { "cmd", "/C", "start", "/B", "test.bat" };
File path = new File("C:/Users/Me/Desktop/dir/");
Runtime.getRuntime().exec(command, null, path);
I have a simple GUI program where one of the features is to ping a destination from a file. I have the ping running fine when using normal ping x.x.x.x however when running this with the -t command i have noticed that even after closing the command window ping.exe is still showing in the process list. I know the process can be ended using ctrl+c but is there a different way to get the process to end when the user closes the cmd window?
i am currently using this code:
try {
ipPing = VNC.getIp().concat(ext);
String command = "ping " + ipPing;
Runtime rt = Runtime.getRuntime();
rt.exec(command);
rt.exec(new String[]{"cmd.exe", "/C", "\"start;" + command + "\""});
} catch (IOException e) {
}
any advice and tips would be greatly appreciated
I'm not sure will it work, but you can try Process.destroy(). Something like this:
ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/C", "\"start;" + command + "\"");
Process p = pb.start();
//...
p.destroy();
Also, don't write empty catch blocks:
} catch (IOException e) {
}
because if an exception gets thrown it'll be hard to notice. Unless of course, you know that you can ignore the exception.
UPDATE:
proof of concept for linux os:
public static void main(String[] args) throws IOException {
ProcessBuilder pb = new ProcessBuilder("ping","localhost");
pb.redirectErrorStream(true);
Process p = pb.start();
InputStreamReader isr = new InputStreamReader(p.getInputStream());
int ch,count = 0;
StringBuffer sb = new StringBuffer();
while((ch =isr.read()) > -1) {
sb.append((char)ch);
if ((char)ch == '\n') {
System.out.println( sb.toString());
sb = new StringBuffer();
}
if (count++ == 2) {
System.out.println("destroying process");
p.destroy();
}
}
}
outputs:
destroying process
PING localhost (127.0.0.1) 56(84) bytes of data.
Exception in thread "main" java.io.IOException: Stream closed
64 bytes from localhost (127.0.0.1): icmp_req=1 ttl=64 time=0.031 ms
at java.io.BufferedInputStream.getBufIfOpen(BufferedInputStream.java:145)
at java.io.BufferedInputStream.read(BufferedInputStream.java:308)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:264)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:306)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:158)
at sun.nio.cs.StreamDecoder.read0(StreamDecoder.java:107)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:93)
at java.io.InputStreamReader.read(InputStreamReader.java:151)
at com.infobip.rhino.Killer.main(Killer.java:24)
Java Result: 1
the lines are messed up because the error stream is redirected to output stream
I am trying to fire the following command on a windows(that came as part of a product we have bought):
start /wait setup /z"/sfC:\temp\input_file.txt" /s /f2"C:\temp\newlogfile.log"
Now the sad part is that I am failing to run the command using a java program that I wrote. (I have to run it as a part of something else, hence the need of running it through java)
Here is my code:
String[] cmd = new String [6];
cmd[0] = "start";
cmd[1] = "/wait";
cmd[2] = "setup";
cmd[3] = "/z\"/sfC:\\temp\\input_file.txt\"";
cmd[4] = "/s";
cmd[5] = "/f2\"C:\\temp\\newlogfile.log\"";
try
{
Runtime.getRuntime().exec(cmd);
}
catch(IOException e)
{
e.printStackTrace();
}
Please tell me what I am doing wrong here.
This is the output I am getting:
java.io.IOException: CreateProcess: start /wait setup /z"/sfC:\temp\input_file.txt" /s /f2"C:\temp\newlogfile.log" error=2
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.<init>(ProcessImpl.java:108)
at java.lang.ProcessImpl.start(ProcessImpl.java:56)
at java.lang.ProcessBuilder.start(ProcessBuilder.java:466)
at java.lang.Runtime.exec(Runtime.java:607)
at java.lang.Runtime.exec(Runtime.java:480)
at SilentAgent.fireCommand(SilentAgent.java:316)
at mainClass.main(mainClass.java:15)
Try with this:
String[] cmd = {
"cmd.exe",
"/c",
"start",
"/wait",
"setup",
"/z\"/sfC:\\temp\\input_file.txt\"",
"/s",
"/f2\"C:\\temp\\newlogfile.log\""
};
Runtime.getRuntime().exec(cmd);
Reason: start is an internal command available only from inside a cmd shell.
Do this way:-
Runtime.getRuntime().exec(new String[] {
"start ",
"/wait ",
"setup ",
"/z\"/sfC:/temp/input_file.txt\" ",
"/s ",
"/f2\"C:/temp/newlogfile.log\""});
Are you sure that you java program is located in the same directory of the 'start' program?
If not, pass the command string as a whole string
try {
String command = "start /wait setup /z\"/sfC:\\temp\\input_file.txt\" /s /f2\"C:\\temp\\newlogfile.log\"";
// The third parameter is the current working directory
Process p = runtime.exec(c, null, new File());
} catch (Exception e) {
e.printStackTrace();
}