I have java code which should stop windows service
When i try it on other commands which do not need admin permissions that works great but to stop windows service i have to start command line as administrator
I tried for example code to start notepad just for checking if this cooperation java with command line works great.
String[] start = {"cmd.exe", "/c", "start", "notepad"};
Process runtimeProcess = Runtime.getRuntime().exec(start);
int processComplete = runtimeProcess.waitFor();
but if i try command to run command line as administrator that failed:
String[] startAsAdmin= new String [] {
"CMD.EXE",
"/C",
"RUNAS /profile /user:"
+ "administrator"
+ " ", "start", "notepad"};
Process runtimeProcess = Runtime.getRuntime().exec(startAsAdmin);
runtimeProcess.waitFor();
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(runtimeProcess.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(runtimeProcess.getErrorStream()));
BufferedWriter stdOutput = new BufferedWriter(new
OutputStreamWriter(runtimeProcess.getOutputStream()));
read the output from the command and put my original password to command line
when password is required (Zadejte heslo pro administrator means password required in english)
System.out.println("Here is the standard output of the command:\n");
String s = null;
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
if (s.startsWith("Zadejte heslo pro administrator:")) {
stdOutput.append("password").flush();
}
}
Why if i put my original password to command line like this it didn't works? It said Access Denied, but im sure that password is right and the next question is is there any possible way how can i do it without show my password in code?
Ohhh sry i now see ur update, but it still didn't start notepad:
String[] startAsAdmin= new String [] {
"CMD.EXE",
"/C",
"echo password123 | RUNAS /profile /user:"
+ "administrator"
+ " ", "start", "notepad"};
Process runtimeProcess = Runtime.getRuntime().exec(startAsAdmin);
int processComplete = runtimeProcess.waitFor();
You Should try this:
String[] stopAdmin= new String [] {
"CMD.EXE",
"/C",
"echo password123 | RUNAS /profile /user:"
+ "administrator"
+ " ", "net", "stop", Service_Name};
Process runtimeProcess = Runtime.getRuntime().exec(stopAdmin);
Hope this helps.
Related
Hey all I am trying to change directories and then run my command with parameters.
final String path = "\\Local// Apps\\IBM\\SDP\\scmtools\\eclipse";
final String command = "scm help";
final String dosCommand = "cmd /c \"" + path + "\"" + command;
final Process process = Runtime.getRuntime().exec(dosCommand);
final InputStream in = process.getInputStream();
int ch;
while((ch = in.read()) != -1) {
System.out.print((char)ch);
}
It runs without errors but outputs nothing. However, this is what shows up after it finishes:
<terminated, exit value: 0>C:\Local Apps\IBM\SDP\jdk\bin\javaw.exe (Jul 22, 2019, 11:21:37 AM)
The expected output should be:
So am I doing this correctly?
AS suggested by Andreas
Process p = null;
ProcessBuilder pb = new ProcessBuilder("scm.exe");
pb.directory(new File("C:/Local Apps/IBM/SDP/scmtools/eclipse"));
p = pb.start();
I get the following error:
Cannot run program "scm.exe" (in directory "C:\Local Apps\IBM\SDP\scmtools\eclipse"): CreateProcess error=2, The system cannot find the file specified
You should use ProcessBuilder instead of Runtime.exec, e.g.
Process proc = new ProcessBuilder("scm.exe", "help")
.directory(new File("C:\\Local Apps\\IBM\\SDP\\scmtools\\eclipse"))
.inheritIO()
.start();
proc.waitFor(); // optional
You can also go through the command interpreter if needed, e.g. if the command is a script (.bat or .cmd file):
Process proc = new ProcessBuilder("cmd", "/c", "scm", "help")
.directory(new File("C:\\Local Apps\\IBM\\SDP\\scmtools\\eclipse"))
.inheritIO()
.start();
proc.waitFor();
The inheritIO() means that you don't need to process the commands output. It will be sent to the console, or wherever Java's own output would go.
I would like to execute multiple commands in a cmd shell from java:
sample:
String cmdShell = "cmd /c start cmd.exe /K ";
String endCommand = cmdShell + "\"" + multiplecommands + " && exit" + "\"";
Process proc = Runtime.getRuntime().exec(endCommand);
final BufferedReader input = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = null;
while ((line = input.readLine()) != null) {
LOGGER.debug("" + line);
}
proc.waitFor();
This opens the black window and closes after finished. Is there a way to hide this window. Or any other way to execute multiple commands without showing the cmd window ?
Maybe it useful "start" with "/min":
start /min .....
..........
exit
https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/start
you can try this code , in my case this code give all Directory of C:\xampp folder in my console ...without open CMD
public static void main(String[] args)throws Exception {
ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/c", "cd C:\\xampp && C: && 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);
}
}
for more study you can read this page
I am trying to run a command to read a string from a file inside a remote address (and I'm sure the file is there), this command works when I run it on the bash but it doesn't work when I run it in my java code.
Runtime rt = Runtime.getRuntime();
String[] command;
String line;
try {
command = new String[] {"sh", "-c", "\"sshpass " + "-p " + password + " ssh " + user + "#" + ip + " 'cat " + file.getAbsolutePath() + "'\"" };
Process mountProcess = rt.exec(command);
mountProcess.waitFor();
bufferedReader = new BufferedReader(new InputStreamReader(mountProcess.getInputStream()));
while ((line = bufferedReader.readLine()) != null) {
user_list.put(user, line);
}
bufferedReader.close();
bufferedReader = new BufferedReader(new InputStreamReader(mountProcess.getErrorStream()));
while ((line = bufferedReader.readLine()) != null) {
LOGGER.debug("Stderr: " + line);
}
bufferedReader.close();
} catch ...
No line is added to my user_list (so the line from getInputStream is null) and I get the following error from the logger in the code:
Stderr: sh: 1: sshpass: not found
If I use the exact same command on the bash it works and it prints the string I need.
sshpass -p password ssh remote#192.168.1.10 'cat /home/ID/ID'
Anyone knows why this is happening? thanks!
I'd suggest you don't need to use sh to wrap your command. Try
command = new String[] {"sshpass", "-p", password, "ssh", user + "#" + ip, "cat " + file.getAbsolutePath() };
If you need to use sh, then remove the escaped double quotes from the command string: you are sending those as literal characters:
command = new String[] {
"sh",
"-c",
String.format("sshpass -p %s ssh %s#%s 'cat %s'", password, user, ip, file.getAbsolutionPath())
};
If you're still getting "command not found", then you need to either specify the full path to sshpass, or ensure that its directory is in your PATH.
When doing this command with java the user is tomcat8 instead of root (when used in the bash terminal)
The solution that worked for me included some flags:
String.format("/usr/local/bin/sshpass -p %s /usr/bin/ssh -q -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no %s#%s 'cat %s'", password, user, ip, file.getAbsolutePath());
I want to start/stop a service from my java program for which I am using terminal commands. The problem is that I need to start the terminal as admin for which I am using the ProcessBuilder API.
public void startService(String serviceName) throws IOException, InterruptedException {
String[] cmdArray = {"cmd.exe", "/c",
"runas /savecred /profile /user:admin \"sc start " + serviceName + "\""};
Process process = new ProcessBuilder(cmdArray).start();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
OutputStreamWriter output = new OutputStreamWriter(process.getOutputStream());
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line); //Prints "enter the password for admin"
}
output.write("password"); //my password
output.newLine();
output.flush();
//output.wait();
process.destroy();
}
The command executes fine and it prints Enter the password for admin but when I supply it through the output stream of process, I get the I/O error java.io.IOException: The pipe is being closed. I also tried to add echo mypassword | before the command which does not prompt for password on terminal but is prompting from java program. Any help on this is much appreciated.
EDIT- I am getting the error on output.flush()
I have sendmail file that contains this script echo "sample message" | /usr/bin/swaks --to email#gmail.com I want to run it from java using this code :
ProcessBuilder pb = new ProcessBuilder("sendmail");
Process p = pb.start()
but the email is not sent. Whats wrong and how can i fix this?
edit : running ./sendmail is working, and the email is sent to my mail
I think the problem is that your java application is ending before the script finishes.
Try this:
ProcessBuilder pb = new ProcessBuilder("./sendmail.sh");
Process p = pb.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String readline;
int i = 0;
while ((readline = reader.readLine()) != null) {
System.out.println(++i + " " + readline);
}
The above code should print out what your command prints which could help you debug. It also has the side effect of blocking until the script is finished.
If that works and you don't care about the output, you can do this:
ProcessBuilder pb = new ProcessBuilder("./test.sh");
Process p = pb.start();
p.waitFor();