在某个ip下执行某条命令
在某个ip下执行某条命令
- 根据ip以及服务名称查询该服务安装到的目录
/**
* 获取指定ip下,指定服务名称对应的服务安装目录
* @param ipAddress
* @param serviceName
* @return
*/
public String getDic(String ipAddress, String serviceName) {
String installDir = null;
try {
// 构建命令行指令
ProcessBuilder processBuilder = new ProcessBuilder(
"cmd.exe",
"/c",
"sc \\\\" + ipAddress + " qc " + serviceName + " | findstr BINARY_PATH_NAME"
);
// 执行命令并获取输出结果
Process process = processBuilder.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
String[] path = line.trim().split("\"");
if (path.length > 1) {
File file = new File(path[1]);
installDir = file.getParent();
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return installDir;
}
- 根据ip以及安装到的目录执行cmd命令
/**
* 根据ip以及安装服务的目录执行命令
* @param ipAddress
* @param dic
*/
public static void executeCommand(String ipAddress, String dic) {
// 定义要执行的cmd命令和工作目录
String[] command = {"cmd", "/c", "vncviewer.exe " + ipAddress};
File workingDirectory = new File(dic);
// 使用ProcessBuilder来执行命令
ProcessBuilder builder = new ProcessBuilder(command);
builder.directory(workingDirectory);
builder.redirectErrorStream(true);
Process process = null;
try {
process = builder.start();
} catch (IOException e) {
e.printStackTrace();
}
// 读取命令输出并打印
java.util.Scanner scanner = new java.util.Scanner(process.getInputStream()).useDelimiter("\\A");
String output = scanner.hasNext() ? scanner.next() : "";
System.out.println("output:" + output);
// 等待命令执行完成
int exitCode;
try {
exitCode = process.waitFor();
} catch (InterruptedException e) {
exitCode = -1;
}
// 打印命令执行结果
if (exitCode == 0) {
System.out.println("命令执行成功");
} else {
System.out.println("命令执行失败");
}
}
版权声明:本文为weixin_44021888原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。