How can I make executeShell ask for Admin Elevation?

Ali Çehreli acehreli at yahoo.com
Sun Jul 12 21:50:06 UTC 2020


On 7/11/20 7:10 PM, Marcone wrote:
> I don't want start program with admin elevation, but ask user for admin 
> permission when some function is called.

Here is a hacky solution that attempts the command and fails back to 
asking the password. It should work on POSIX systems. (Tested on Linux.)

import std.stdio;
import std.process;
import std.format;
import std.algorithm;

// Copied the interface from executeShell
auto executeShellSudo(scope const(char)[] command,
                       const string[string] env = null,
                       Config config = Config.none,
                       size_t maxOutput = size_t.max,
                       scope const(char)[] workDir = null,
                       string shellPath = nativeShell) {
   // First assume the user is super user:
   auto suCommand = format!"sudo --non-interactive %s"(command);
   auto execute() {
     return executeShell(suCommand, env, config, maxOutput, workDir, 
shellPath);
   }

   auto result = execute();

   if ((result.status == 1) &&
       (result.output == "sudo: a password is required\n")) {

     // Have sudo ask for password. (Alternatively, sudo can be invoked
     // with the --askpass switch.)
     suCommand = format!"sudo %s"(command);
     result = execute();
   }

   return result;
}

void main() {
   auto result = executeShellSudo("cat /dev/null");
   writeln(result);
}

Ali


More information about the Digitalmars-d-learn mailing list