Tro*_*roy 11 java command-line windows-services
情况如下:
我被要求使用InstallAnywhere 8,这是一个基于Java的安装程序IDE,允许启动和停止Windows服务,但没有内置方法来查询它们的状态.幸运的是,它允许您使用Java创建自定义操作,可以在安装过程中随时调用(通过我认为是一个相当复杂的API).
我只需要一些能告诉我特定服务是否已启动或停止的内容.
IDE还允许调用批处理脚本,所以这也是一个选项,虽然一旦运行脚本,几乎没有办法验证它是否成功,所以我试图避免这种情况.
欢迎任何建议或批评.
Yuv*_*val 15
这就是我必须做的事情.这很难看,但效果很好.
String STATE_PREFIX = "STATE : ";
String s = runProcess("sc query \""+serviceName+"\"");
// check that the temp string contains the status prefix
int ix = s.indexOf(STATE_PREFIX);
if (ix >= 0) {
// compare status number to one of the states
String stateStr = s.substring(ix+STATE_PREFIX.length(), ix+STATE_PREFIX.length() + 1);
int state = Integer.parseInt(stateStr);
switch(state) {
case (1): // service stopped
break;
case (4): // service started
break;
}
}
Run Code Online (Sandbox Code Playgroud)
runProcess是一个私有方法,它将给定的字符串作为命令行进程运行并返回结果输出.正如我所说,丑陋,但有效.希望这可以帮助.
您可以在运行中创建一个小型VBS,启动它并捕获其返回码.
import java.io.File;
import java.io.FileWriter;
public class VBSUtils {
private VBSUtils() { }
public static boolean isServiceRunning(String serviceName) {
try {
File file = File.createTempFile("realhowto",".vbs");
file.deleteOnExit();
FileWriter fw = new java.io.FileWriter(file);
String vbs = "Set sh = CreateObject(\"Shell.Application\") \n"
+ "If sh.IsServiceRunning(\""+ serviceName +"\") Then \n"
+ " wscript.Quit(1) \n"
+ "End If \n"
+ "wscript.Quit(0) \n";
fw.write(vbs);
fw.close();
Process p = Runtime.getRuntime().exec("wscript " + file.getPath());
p.waitFor();
return (p.exitValue() == 1);
}
catch(Exception e){
e.printStackTrace();
}
return false;
}
public static void main(String[] args){
//
// DEMO
//
String result = "";
msgBox("Check if service 'Themes' is running (should be yes)");
result = isServiceRunning("Themes") ? "" : " NOT ";
msgBox("service 'Themes' is " + result + " running ");
msgBox("Check if service 'foo' is running (should be no)");
result = isServiceRunning("foo") ? "" : " NOT ";
msgBox("service 'foo' is " + result + " running ");
}
public static void msgBox(String msg) {
javax.swing.JOptionPane.showConfirmDialog((java.awt.Component)
null, msg, "VBSUtils", javax.swing.JOptionPane.DEFAULT_OPTION);
}
}
Run Code Online (Sandbox Code Playgroud)
根据其他答案,我构建了以下代码来检查 Windows 服务状态:
public void checkService() {
String serviceName = "myService";
try {
Process process = new ProcessBuilder("C:\\Windows\\System32\\sc.exe", "query" , serviceName ).start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
String scOutput = "";
// Append the buffer lines into one string
while ((line = br.readLine()) != null) {
scOutput += line + "\n" ;
}
if (scOutput.contains("STATE")) {
if (scOutput.contains("RUNNING")) {
System.out.println("Service running");
} else {
System.out.println("Service stopped");
}
} else {
System.out.println("Unknown service");
}
} catch (IOException e) {
e.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)