1

Why does the service not get restarted?

void page_maintenance_general::on_rtunnel_restart_Button_clicked()
{
    QProcess process;
    // Seems to work, but in journalctl it's clear it did not execute.
    process.start("echo 'pwdshereshouldbeavoidedIknow' | sudo -S -n systemctl restart rtunnel.service");
    //process.start("nmcli networking connectivity"); // works fine

    process.waitForFinished(-1);
    QString feedback = process.readAllStandardOutput();
    //QString feedback = process.readAllStandardError();
    qDebug() << "rtunnel restart status: " << feedback;
    ui->backend_status_label->setText("rtunnel restart " + feedback);

}
  • For an innocent command, things work well. nmcli networking connectivity gives full
  • echo 'pwdthatshouldbeavoidedIknow' | sudo -S -n systemctl restart rtunnel.service works when executed as the same user that executes the program in a terminal.
  • Other sudo commands work too in the same program e.g.
QString command = "echo 'mypassword' | sudo -S shutdown -r 0"; // works fine
system(qPrintable(command));
Benjamin Buch
  • 4,752
  • 7
  • 28
  • 51
lode
  • 504
  • 6
  • 21

1 Answers1

1

You can not use Pipes in QProcess.start(). After some testing I found out that sudo doesn't work as expected when not called from a command line interpreter.

Start a bash and write your commands to it. Remember to exit the bash! Note that the newline characters in the write's are important!

Note: The -S parameter in sudo is used to read the password from standard input instead of from the terminal.

QProcess process;
process.start("bash");
process.waitForStarted();
process.write("echo 'pwdshereshouldbeavoidedIknow' | sudo -S systemctl restart rtunnel.service\n");
process.write("exit\n");
process.waitForFinished();
lode
  • 504
  • 6
  • 21
Benjamin Buch
  • 4,752
  • 7
  • 28
  • 51
  • Thanks for the input. I was still unsuccessful. Even after executing László Papp's solution from: https://stackoverflow.com/questions/23322739/how-to-execute-complex-linux-commands-in-qt – lode Mar 09 '23 at 23:43
  • 1
    @lode I think my new solution should work for you. On my system I was able to exec commands by sudo. I tested with `sudo -S sleep 3`. – Benjamin Buch Mar 10 '23 at 00:43
  • 1
    Yes, the new solution did the trick. thx! I had to remove the -n from the sudo command too. will edit answer as soon as it allows me to. – lode Mar 11 '23 at 01:38