这里我有以管理员身份保存启动命令行命令的String并停止Windows服务。它在控制台中说:输入管理员的密码:
String administratorCommandLine = "runas /profile /user:Administrator \"cmd.exe /c sc stop AcPrfMgrSvc\"";
Process runtimeProcess = Runtime.getRuntime().exec(administratorCommandLine);
runtimeProcess.waitFor();
BufferedReader stdInput = new BufferedReader(new InputStreamReader (runtimeProcess.getInputStream());
BufferedWriter stdOutput = new BufferedWriter(new OutputStreamWriter(
runtimeProcess.getOutputStream()));
当我想根据需要向命令行添加密码来告诉异常时: 例外:java.io.IOException:管道正在关闭
System.out.println("Here is the standard output of the command:\n");
String s = null;
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
if(s.startsWith("Enter the password for Administrator:") || s.startsWith("Zadejte heslo pro administrator:")) {
stdOutput.append("password123").flush();
}
}
有没有办法将密码放入该流中?
答案 0 :(得分:0)
试试这段代码:
String loggedInUser = System.getProperty("user.name");
String pass="";
String psexec = "C:\\Utils\\psexec.exe"; //location of psexec
//Build the command line
List<String> command = new LinkedList<String>();
command.add(psexec);
command.add("-u");
command.add("Administrator");
//request password if the user is not Administrator
if(! loggedInUser.equalsIgnoreCase("Administrator")) {
Scanner s = new Scanner(System.in);
System.out.print("Password: ");
pass = s.nextLine();
if(! pass.trim().isEmpty()) {
command.add("-p");
command.add(pass);
}
}
command.add("cmd.exe");
String[] cmdArgs = {"/c", "sc", "stop", "AcPrfMgrSvc"};
command.addAll(Arrays.asList(cmdArgs));
ProcessBuilder builder = new ProcessBuilder(command);
Process process = builder.start();
int returnCode;
try {
returnCode = process.waitFor();
} catch (InterruptedException e) {
returnCode = 1;
}
PS:我知道将密码读作字符串使用Scanner是不安全的,不是一个好主意。我上面的代码主要是为了演示如何使用PsExec以管理员身份停止Windows服务。您应该使用更好的版本替换密码阅读代码,如http://docs.oracle.com/javase/tutorial/essential/io/cl.html
所述