工具类
/**
* 运行Linux命令
* @param commands 命令集合
* @return 返回结果
*/
public static List<String> executeNewFlow(List<String> commands)
{
List<String> rspList = new ArrayList<String>();
Runtime run = Runtime.getRuntime();
try
{
Process proc = run.exec("/bin/bash", null, null);
BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())), true);
for (String line : commands)
{
out.println(line);
}
out.println("exit");// 这个命令必须执行,否则in流不结束。
String rspLine = "";
while ((rspLine = in.readLine()) != null)
{
System.out.println(rspLine);
rspList.add(rspLine);
}
proc.waitFor();
in.close();
out.close();
proc.destroy();
} catch (IOException | InterruptedException e1)
{
e1.printStackTrace();
}
return rspList;
}
demo-修改linux系统时间
/**
* 手动设置时间
* @param dateStr
* @return
*/
@RequestMapping(value = "/setDeviceDate", method = RequestMethod.GET)
@ApiOperation(value = "手动设置时间", httpMethod = "GET")
public ResultObj setDeviceDate(@RequestParam(value = "dateStr") String dateStr)
{
ResultObj resultObj = null;
try {
resultObj = ztbgDeviceInfoAppService.setDeviceDate(dateStr);
} catch (Exception e) {
logger.error("手动设置时间失败!", e);
}
return resultObj;
}
public ResultObj setDeviceDate(String dateStr) {
List<String> cmd = new ArrayList<>();
cmd.add("date -s \"" + dateStr + "\"");
cmd.add("hwclock --systohc");
ShellUtil.executeNewFlow(cmd);
return ResultObjUtils.resultSuccess("设置时间成功");
}