[英]executing kafka sh script remotely from java program
我正在嘗試執行一個 kafka 腳本來檢索主題、消費者組和滯后信息。 我不斷收到錯誤信息,並在此論壇和其他論壇中搜索發現相互矛盾的信息。 有人說不可能在 Unix 上從 Windows 執行遠程腳本,而其他人則給出了一些關於如何嘗試更正此錯誤的建議。 我能夠連接並運行一個簡單的 ping 命令並能夠檢索響應。 也許我在這里遺漏了一個簡單的被忽視的錯誤。
這是代碼:
try {
jsch.setKnownHosts("C:\\Users\\.ssh\\ssh_host_rsa_key.pub");
Session session = jsch.getSession(uname, host, 22);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.setPassword(pword);
session.connect();
Process p = Runtime.getRuntime().exec("./usr/kafka/bin/
kafka-consumer-groups.sh --bootstrap-server 192.xxx.xx.xxx:9092
--describe -group OPSII");
InputStream scriptStdout = p.getInputStream();
BufferedReader scriptReader= new BufferedReader(new
InputStreamReader(scriptStdout));
String scriptOutput = scriptReader.readLine();
StringBuilder sb = new StringBuilder();
while ((scriptOutput = scriptReader.readLine())!= null) {
sb.append(scriptOutput + "\n");
}
scriptStdout.close();
錯誤:
Exception in thread "main" java.io.IOException: Cannot run program
"./usr/kafka/bin/kafka-consumer-groups.sh": CreateProcess
error=2, The system cannot find the file specified
at java.lang.ProcessBuilder.start(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
我已經確認腳本在遠程 unix 機器上工作並且目錄是正確的。 可能是格式嗎,應該是“//”而不是“/”嗎? 究竟是什么導致了這個錯誤? 請這不是一個重復的問題,因為其他提出的解決方案都不起作用。
您可以使用以下代碼通過JSch
運行腳本
// open a channel
channel = session.openChannel("exec");
// type in your command
String command = "./path/to/your_script.sh --add_params \n";
//Below command will execute the data you set in the previous line
((ChannelExec) channel).setCommand(command);
channel.connect();
請注意,這僅使用JSch
庫。
編輯:根據您的評論,您還想從控制台獲取輸出以用於該用途:
InputStream in = channel.getInputStream();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.