2

I handle the normal copying of files with Qt like this:

QFile::copy("/path/file", "/path/copy-of-file");

How can I now copy a file for which Sudo rights are required.

Sonya
  • 53
  • 5

2 Answers2

1

You can use QProcess and pkexec to execute a command as another user

pkexec allows an authorized user to execute PROGRAM as another user. If username is not specified, then the program will be executed as the administrative super user, root.

https://www.freedesktop.org/software/polkit/docs/0.105/pkexec.1.html

QProcess *proc = new QProcess(this);
proc->waitForFinished();

QString cmd = "pkexec /bin/cp /path/file /path/copy-of-file";

proc->start(cmd);

if(!proc->waitForStarted()) //default wait time 30 sec
{
    qDebug() << "Cannot execute:" << cmd;
}

proc->waitForFinished();
proc->setProcessChannelMode(QProcess::MergedChannels);

if(proc->exitStatus() == QProcess::NormalExit
        && proc->exitCode() == QProcess::NormalExit){
    qDebug() << "Success";
} else {
    qDebug() << "Cannot copy file" << cmd;
}
Adriano Campos
  • 1,121
  • 7
  • 14
-1

run shell command, like this

sudo cp /path/file /path/copy-of-file

Set a password if necessary.:

$echo <password> | sudo -S <command>
deMax
  • 86
  • 7
  • yes but this way is not particularly QT compliant. Something like that is a little closer to the system, but not Qt internally either. system(qPrintable("gksudo cp X Y")); – Sonya Oct 09 '18 at 11:31
  • 2
    command sudo is only in linux(qt is cross platform). May by use QAbstractFileEngine for some abstraction, but you have to use the shell command anyway. – deMax Oct 09 '18 at 12:08
  • It is a program that of course should only run on Linux. I forget again and again that there are still people who have to struggle with something else. :D – Sonya Oct 09 '18 at 14:27
  • @Sonya Then, if you're not trying to follow the cross-platform architecture, what's wrong with running the `"gksudo cp src dst"` with `system()` or `QProcess`? – John Doe Oct 09 '18 at 15:29
  • @John Doe the danger of crashes increases enormously with many system(); requests. handling with QProcess offers a more elegant solution for the control process, but unfortunately also stumbles with multiple use. – Sonya Oct 09 '18 at 17:21