Reputation: 115
I'm building functionality to restart windows services remotely, but the string command that I built in code is not returning the desired output, copying the same command while debugging from the IDE and running it on CMD executes successfully.
I have tried changing from using method Process cmdOutput Runtime.getRuntime().exec(command) to Process cmdOutput Runtime.getRuntime().exec(command[]) I have tried manipulating my string command in different ways to see if it will take it with no success.
I have looked at similar questions on StackOverflow but none of them are experiencing what I am experiencing
public void startService(int serviceId, String serviceName, String
ipAddress) {
CMDExecutor executor = new CMDExecutor();
try {
String command = "cmd /C echo "+ password +" runas /user:"+
username +" "+ "\""+
System.lineSeparator() +" sc\\\\" +ipAddress+ " start "+
serviceName + "\"";
String result = executor.getCMDResult(command);
logger.info(result);
}
public class CMDExecutor {
public String getCMDResult(String command) throws IOException {
Process cmdOutput;
cmdOutput = Runtime.getRuntime().exec(command);
StringWriter writer = new StringWriter();
IOUtils.copy(cmdOutput.getInputStream(), writer, "UTF-8");
return writer.toString();
}
}
I'm expecting the below
SERVICE_NAME: serviceName
TYPE : 10 WIN32_OWN_PROCESS
STATE : 2 START_PENDING
(NOT_STOPPABLE, NOT_PAUSABLE, IGNORES_SHUTDOWN)
WIN32_EXIT_CODE : 0 (0x0)
SERVICE_EXIT_CODE : 0 (0x0)
CHECKPOINT : 0x0
WAIT_HINT : 0x7d0
PID : 34916
FLAGS :
I'm getting part of the command back and nothing changes, service doesn't start.
Upvotes: 0
Views: 133
Reputation: 115
After struggling for hours the simple solution was to split the commands into two parts, the credentials part, and the sc command part as per below. Now it works as expected.
PS. I opted to remove echo from the command to avoid credentials getting printed on the log file.
public void startService(int serviceId, String serviceName, String
ipAddress) {
CMDExecutor executor = new CMDExecutor();
try {
String credentialsCommand = "cmd /C echo "+ password +" runas /user:"+ username;
String startServiceCommand = "sc\\\\" +ipAddress+ " start "+ serviceName";
String credentialsResult = executor.getCMDResult(credentialsCommand );
logger.info(credentialsResult );
String startServiceResult= executor.getCMDResult(startServiceCommand );
logger.info(startServiceResult);
}
Upvotes: 0