为了使非root用户可以更新系统时间,
需要设置运行Java程序的用户拥有不输入密码进行/bin/date调用的权限,
此处我运行Java程序的用户为iuser, 操作步骤如下:
使用root登录,
查看sudoers文件权限
ls /etc/sudoers
为用户添加写权限
chmod u+w /etc/sduoers
编辑 sudoers 文件,添加需要提升权限的用户,找到 ## Allow root to run any commands anywhere 这一行,在root用户下添加一行,如下:
iuser ALL=(ALL) NOPASSWD:/bin/date
其中iuser 是需要提权的用户名
否则同步服务器时间无法修改端服务器的时间
java代码如下,仅供参考:
@RequestMapping("/syncServerTime")
@ResponseBody
public void syncServerTime(@RequestParam("datetime") String datetime) {
String date = datetime.substring(0,8);
String time = datetime.substring(8,10)
+ ":" + datetime.substring(10,12)
+ ":" + datetime.substring(12,14);
String osName = System.getProperty("os.name");
try {
if(osName.matches("^(?i)Windows.*$")) {
Runtime.getRuntime().exec("cmd /c date "+date);
Runtime.getRuntime().exec("cmd /c time "+time);
} else {
Runtime.getRuntime().exec("sudo date -s "+date);
Runtime.getRuntime().exec("sudo date -s "+time);
}
log.info("updatetime---->"+datetime);
} catch (IOException e) {
e.printStackTrace();
}
}
访问:http://localhost:8080/syncServerTime?datetime=20220510091333