Ubuntu24.04 赋予 Qt 应用程序 修改系统时间 权限

1、情况简介

由于Ubuntu24.04对于安全性的考虑,以用户身份(非sudo)运行的应用程序无法直接修改内核时间,只能转而进行权限配置来修改系统时间。

2、具体操作

1、Settings-System-Date & Time 取消 Automatic Data & Time

2、GroundStation是我的应用名,pi是我的用户名,你需要自行改为自己的

bash 复制代码
sudo nano /etc/polkit-1/rules.d/allow-GroundStation-time-setting.rules

在文件中写入:

bash 复制代码
// Allow a specific user to set the time without a password
polkit.addRule(function(action, subject) {
    if (action.id == "org.freedesktop.timedate1.set-time" && subject.user == "pi") {
        return polkit.Result.YES;
    }
});

3、Qt程序示例

cpp 复制代码
bool HeartBeatReceiver::setSystemTime(u64 Timestamp_us)
{ 
    // --- 1. 将微秒时间戳转换为 QDateTime 对象并验证 ---
    QDateTime dateTime = QDateTime::fromMSecsSinceEpoch(Timestamp_us / 1000);
    dateTime.setTimeSpec(Qt::UTC); // 时间戳通常是 UTC

    int year = dateTime.date().year();
    if (year < 2025 || year > 2030) {
        qDebug() << "Validation failed: Year " << year << " is not within the required range [2025, 2030].";
        return false;
    }
    qDebug() << "Validation passed. The year is " << year << ".";

    QProcess process;
    bool timeSetSuccess = false;

    // --- 2. 设置系统时间 ---

    QString formattedTime = dateTime.toString("yyyy-MM-dd hh:mm:ss");
    qDebug() << "Attempting to set system time..." << formattedTime;
    process.start("timedatectl", QStringList() << "set-time" << formattedTime);

    if (!process.waitForFinished(5000)) {
        qDebug() << "Error: 'timedatectl set-time' command timed out.";
    } else if (process.exitCode() == 0) {
        qDebug() << "System time set successfully!";
        timeSetSuccess = true;
    } else {
        qDebug() << "Error: Failed to set system time.";
        qDebug() << "Exit Code:" << process.exitCode();
        qDebug() << "Standard Error:" << process.readAllStandardError();
    }

    return timeSetSuccess;
}
相关推荐
学无止境_永不停歇22 分钟前
9. 缓冲区
linux·服务器·c++
dok1227 分钟前
Johannes 《Linux内核模块与设备驱动开发:编写Linux驱动程序》(4) devicefile 设备号相关
linux·运维·服务器
Fu2067211 小时前
结课项目考试
linux·运维·服务器
Albert·Lin1 小时前
LVS相关知识点总结-一
linux·服务器·lvs
tianyuanwo3 小时前
深入理解 Linux 启动救援模式与控制台选择:从 x86 的 tty0 到 ARM 的 ttyS0
linux·grub·救援系统
瞬间&永恒~3 小时前
【MySQL】练习5-1:配置慢查询日志
linux·运维·云原生
邪修king3 小时前
Re:Linux系统篇(四):权限Chapter--用户身份、权限位与目录权限三大核心问题
linux·运维·服务器
buhuizhiyuci4 小时前
【Linux 篇】数字世界的通信管道 —— 匿名管道与进程池深度实战解析
linux·运维·服务器
道尔柯南4 小时前
【Linux】基础开发工具Vim
linux·运维·vim
江南风月4 小时前
WGCLOUD是如何监控服务器上的异常进程的
linux·运维·服务器