Executing Linux command as root in Qt
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)开发者_JS百科;
QString p_stdout = p.readAllStandardOutput();
QString p_stderr = p.readAllStandardError();
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.
Probably something can be done with void QProcess::setEnvironment ( const QStringList & environment )
?
Thanks
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.
精彩评论