2

I need to execute code with admin rights at many places. I find sudo.exe and successfully prompt user for permission and password. I still could not figure out how exactly to use sudo.exe. As I am getting same error of permission denied while deleting a file that need admin permission. That is how my code looks like:

const fs = require('fs')
var sudo = require('sudo-prompt');

var options = {
    name: 'Electron',
};

sudo.exec('echo hello', options,
    function(error, stdout, stderr) {
    if (error) throw error;

    // Code that I want to run with admin rights

    fs.unlinkSync("/private/var/log/fsck_hfs.log", (err) => {
        alert("File succesfully deleted");
    });
}
);

I think this method can only be used to run command, like echo hello in this case. What if I actually want to execute a chunk of code instead of a command? Does this method works or these is any other approach available?

Is there a better method available in Electron to get privileges?

Nargis
  • 739
  • 7
  • 30
  • `sudo-prompt` will get the command you pass it higher privileges, not the code you're running in the callback. You have to call `sudo.exec ()` for every command you want to execute. For example: `sudo.exec ("rm /private/var/log/fsck_hfs.log", options, (e, stdout, stderr) => {});` – Alexander Leithner Jan 06 '19 at 18:42

1 Answers1

0

You can see the admin prompt approach in a popular Electron app: https://github.com/microsoft/vscode

In the package.json file they have two useful dependencies:

They check to see if permissions are elevated using native-is-elevated, and if not, prompt for an admin password using sudo-prompt.

You can read the source code for the process here: https://github.com/microsoft/vscode/blob/8845f89c1e4183b54126cd629cd45c8f0f7549f2/src/vs/platform/native/electron-main/nativeHostMainService.ts#L491

I have created an example Electron app using this approach here: https://github.com/kmturley/electron-runas-admin

If you want to run Node.js code, you can put it inside a script.js and run: node script.js

Kim T
  • 5,770
  • 1
  • 52
  • 79