我正在构建远程重启 Windows 服务的功能,但我在代码中构建的字符串命令没有返回所需的输出,从 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 :我得到了命令的一部分,但没有任何变化,服务没有启动。
1 回答
慕田峪9158850
TA贡献1794条经验 获得超7个赞
经过几个小时的努力,简单的解决方案是将命令分为两部分,凭证部分和 sc 命令部分,如下所示。现在它按预期工作。
附言。我选择从命令中删除 echo 以避免在日志文件中打印凭据。
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);
}
添加回答
举报
0/150
提交
取消