在 Qt 中以 root 身份执行 Linux 命令 [英] Executing Linux command as root in Qt

查看:70
本文介绍了在 Qt 中以 root 身份执行 Linux 命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以 root 用户身份从我的 C++/Qt 代码中执行一个 linux 命令.最终应该实现一个请求 root 密码的对话框,但我不能硬编码 root 密码.

I want to execute a linux command as a root user, from my C++/Qt code. Ultimately a a dialog requesting root pass should be implemented, but for no I can hard-code root password.

这是我到目前为止所做的:

This is what I done so far:

QProcess p;
p.start( "dmidecode" );
p.waitForFinished(-1);

QString p_stdout = p.readAllStandardOutput();
QString p_stderr = p.readAllStandardError();

它适用于不请求 root 权限的命令.但是我想实现像zypper up"或dmidecode"这样的命令,如果没有root密码我就无法执行.

And it is working for commands that do not request root privileges. But I want to implement commands like "zypper up" or "dmidecode" which I can't execute without a root password.

也许可以用 void QProcess::setEnvironment (const QStringList & environment)?

谢谢

推荐答案

如果您以普通用户身份运行,则无法提升您的权限,除非您是 suid,而您可能不希望整个应用程序都使用它.
它的完成方式是通过外部助手;你想要一些 sudo 而不是 su 的东西,因为在 Ubuntu 中 root 帐户被锁定;gksudo 或 kdesudo 取决于运行环境.其中一个应该预先安装在任何现代 Linux 发行版上,或者您可以使用您的应用程序部署一个副本.
当然,如果当前用户没有权限通过 sudo 运行东西,它就不会起作用,但这是一种正常的安全措施,你不应该绕过它.

You cannot elevate your privileges if you run as a normal user unless you're suid, which you probably don't want for the whole application.
The way it's done is through an external helper; you want something that does sudo not su as in Ubuntu the root account is locked; gksudo or kdesudo depending on the running environment. One of those should be preinstalled on any modern linux distro, or you could deploy a copy with your application.
Of course it will not work if the current user does not have the rights to run stuff through sudo, but this is a normal security measure and you shouldn't work around it.

这篇关于在 Qt 中以 root 身份执行 Linux 命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆