我正在构建用于远程重新启动Windows服务的功能,但是我内置代码中的string命令未返回所需的输出,在从IDE调试时复制同一命令并在CMD上运行该命令可以成功执行。
我尝试从使用Process cmdOutput Runtime.getRuntime()。exec(command)方法更改为Process cmdOutput Runtime.getRuntime()。exec(command [])方法 我尝试用不同的方式来操作我的字符串命令,看看是否会成功。
我在StackOverflow上查看了类似的问题,但没有一个遇到我所遇到的问题
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();
}
}
我期待以下
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 :
我正在返回命令的一部分,并且没有任何变化,服务没有启动。
答案 0 :(得分:0)
经过数小时的奋斗,简单的解决方案是将命令分成两部分,分别是凭据部分和sc命令部分,如下所示。现在它可以正常工作了。
PS。我选择从命令中删除回显,以避免凭据被打印在日志文件中。
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);
}