[英]Run a cmd command in Java that asks for another input
我應該使用 Java 運行命令。
命令是: mosquitto_ctrl -u admin -P admin dynsec createClient User
運行命令后,它要求我輸入兩次,如下所示:
輸入用戶的新密碼。 無密碼按回車(用戶將無法登錄)。
用戶的新密碼:
接着:
重新輸入用戶密碼:
當程序自動向 cmd 提供輸入時,我該怎么辦?
我試圖寫這個 function 但它不起作用:
public static void createMosquittoUser(String username, String password) throws IOException {
ProcessBuilder builder = new ProcessBuilder(
"cmd.exe", "/c", "cd \"C:\\mosquitto\" && mosquitto_ctrl -u admin -P admin dynsec createClient " + username);
builder.redirectErrorStream(true);
Process p = builder.start();
OutputStream os = p.getOutputStream();
os.write(password.getBytes());
os.write(password.getBytes());
os.close();
BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while (true) {
line = r.readLine();
if (line == null) { break; }
System.out.println(line);
}
}
我該如何修復它,以便它自動執行所有命令?
要為流程提供行尾,您需要將System.lineSeparator()
發送到 stream。 這應該提供密碼作為一個完整的輸入行:
os.write(password.getBytes());
os.write(System.lineSeparator().getBytes());
您要發送兩次password
(或者您應該先發送用戶名,然后再發送密碼?)如果您通過重復上述語句發送兩行輸入,它可能會起作用,但由於輸入的方式,這可能無法按預期工作在此過程中緩沖,因此您可能需要在每個os.write
之間從p.getInputStream()
讀取一行(如@Michael建議的那樣)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.