Java 更新服务器日期时间

为了使非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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值