我有一个停止并启动Windows服务的java应用程序。我要求它应该能够在远程计算机上执行此操作。我用于远程启动Windows服务的当前代码如下所示:
public void executeCommand() {
String[] command = {"cmd.exe", "/c", "sc", "\\\\192.168.1.27", "start", "btwdins"};
try {
Process process = new ProcessBuilder(command).start();
InputStream inputStream = process.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
} catch (Exception ex) {
System.out.println("Exception : " + ex);
}
}
但是在运行时我收到以下错误:
[SC] OpenSCManager FAILED 5:
Access is denied.
请注意以下事项:
本地和远程计算机都在Windows 10上运行
远程计算机已禁用防火墙
RPC(远程过程调用)正在远程计算机上运行
远程计算机上打开了文件和打印机共享
我错过了什么?任何帮助将不胜感激。
答案 0 :(得分:0)
您可以尝试从互联网下载PsExec.exe并编写以下代码。
公共类RemoteConnection {
static String psCommandStart = null;
static String psCommandStop = null;
public static void main(String[] args) {
String currentServerHostname="192.168.0.1";
String currentServerUser="Administrator";
String currentServerPass="admin";
String commandToStart="net start ServiceName";
String commandToStop="net stop ServiceName";
String psCommand = "D://Workspace //PsExec.exe \\\\"+ currentServerHostname + " -u " + currentServerUser + " -p " + currentServerPass;
psCommandStart = psCommand + " " + commandToStart;
psCommandStop = psCommand + " " + commandToStop;
ServiceStart();
ServiceStop();
}
private static void ServiceStop() {
String[] cmd = new String[5];
cmd[0]="cmd.exe";
cmd[1]="/C";
cmd[2]=psCommandStop;
cmd[3]="";
cmd[4]="";
// Run remote command
File f = new File(getCurrentWorkingDirectory() + "\\lib");
try
{
Process run = Runtime.getRuntime().exec(cmd,null,f);
}
catch (IOException e)
{
e.printStackTrace();
}
}
private static void ServiceStart() {
String[] cmd = new String[5];
cmd[0]="cmd.exe";
cmd[1]="/C";
cmd[2]=psCommandStart;
cmd[3]="";
cmd[4]="";
// Run remote command
File f = new File(getCurrentWorkingDirectory() + "\\lib");
try
{
Process run = Runtime.getRuntime().exec(cmd,null,f);
}
catch (IOException e)
{
e.printStackTrace();
}
}
private static String getCurrentWorkingDirectory() {
String currentDir = System.getProperty("user.dir");
return currentDir;
}
}