Executing Linux command as root in Qt

﹥>﹥吖頭↗ 提交于 2019-12-01 10:59:48

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.

Add a rule to the list of sudoers for a special user, and execute the command as this user as:

sudo *some command*

You can use system() or QProcess for this.

To see how to add a rule to the list of sudoers, see sudoers manual

How about keep using your code anyway but make a shell script for your app and put it on /usr/bin? I did it and works well everytime.

#it is the shell script code
#!/bin/bash
gksudo /usr/lib/your_qt_app

Than simply you just need to call the shell script file. Name it myscript and open your bash. Type there:

myscript

Notice the gksudo command above. That command elevates you to be root. I don't know simpler answer than this. Maybe it doesn't help, but I use this way.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!