java通過http服務執行shell命令


服務端代碼
/**
* 執行shell命令
* @param command 執行命令
* @return
*/
public String exeCommandByPath( String command){
log.info("進入執行shell命令方法 執行命令:" + command);
String returnString = "";
Process pro = null;
String[] cmds = { "/bin/sh", "-c", command };
Runtime runTime = Runtime.getRuntime();
if (runTime == null) {
log.info("Create runtime false!");
}
try {
pro = runTime.exec(cmds);
BufferedReader input = new BufferedReader(new InputStreamReader(pro.getInputStream()));
PrintWriter output = new PrintWriter(new OutputStreamWriter(pro.getOutputStream()));
String line;
while ((line = input.readLine()) != null) {
returnString = returnString + line + "\n";
}
input.close();
output.close();
pro.destroy();
} catch (Exception ex) {
log.info("執行shell命令出現異常" + ex.getMessage());
}
log.info("執行shell命令方法結果" + returnString);
return returnString;
}

客戶端代碼
/**
* 執行shell命令
*
* @param command 執行命令
* @return
*/
public String exeCommandByPath(String command) throws Exception {
Response response = null;
try {

Client client = ClientBuilder.newClient();
WebTarget target = client.target(路徑(http://.....)).queryParam("command", command);
client.property(ClientProperties.CONNECT_TIMEOUT, 2000);
client.property(ClientProperties.READ_TIMEOUT, 10);
response = target.request().get();
if (response.getStatus() == 200) {
String result = response.readEntity(String.class);
log.error("執行shell命令時{}返回值", result);
return result;
} else {
throw new Exception("執行shell命令時連接失敗!");
}
} catch (Exception e) {

log.error("執行shell命令時{}出現異常", command, e);
throw new Exception("執行shell命令時{}" + command + "出現異常:" + e.getMessage());
} finally {
log.info("執行shell命令時{}", command);

}
}

客戶端和服務端通過restful進行http關聯



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM