1

I am developing a small project using dotnetcore on Ubuntu 16.04 to execute some simple commands. This is the code I used to run commands

public void ExecuteCommand(string command)
{
    Process proc = new Process();
    proc.StartInfo.FileName = "/bin/bash";
    proc.StartInfo.Arguments = "-c \" " + command + " \"";
    proc.StartInfo.UseShellExecute = false;
    proc.StartInfo.RedirectStandardOutput = true;
    proc.Start();

    while (!proc.StandardOutput.EndOfStream)
    {
        Console.WriteLine(proc.StandardOutput.ReadLine());
    }
}

When I tried to use sudo command with above code such as sudo service nginx restart, then I ran the program but the program showed console for me to enter root password. So how can I execute sudo command without entering password directly on console?

Dotnetcore info on my machine

.NET Command Line Tools (1.0.0-preview2-1-003177)

Product Information:
 Version:            1.0.0-preview2-1-003177
 Commit SHA-1 hash:  a2df9c2576

Runtime Environment:
 OS Name:     ubuntu
 OS Version:  16.04
 OS Platform: Linux
 RID:         ubuntu.16.04-x64
Tan Viet
  • 1,983
  • 6
  • 25
  • 36
  • You can run your program as root. Then it should be able to execute commands with root rights without re-authorizing. Otherwise there is no way I know to get around the password and there shouldn't be. If a program can execute root commands on my machine without my explicit authorization, this would be a big security risk. – André Stannek Dec 12 '16 at 08:45
  • 1
    @AndréStannek Yes you can: http://askubuntu.com/a/147265 but I'm with you, this shouldn't be done. On the other hand you can limit sudo to certain applications http://askubuntu.com/a/39294 – mistapink Dec 12 '16 at 09:56
  • Possible duplicate of [How to run sudo command without password from java program?](http://stackoverflow.com/questions/10732526/how-to-run-sudo-command-without-password-from-java-program) – mistapink Dec 12 '16 at 09:58
  • @mistapink didn't consider this because I had the impression OP was looking for an "in-code-solution" so to speak. If you have that kind of access to a machine, it is way more comfortable (and safe!) to just run the program as root. Still +1 :-) – André Stannek Dec 12 '16 at 10:11

2 Answers2

1

You can run your program as root or just add the user to the sudo group. or open the sudoers file: sudo visudo and add user all privileges by adding line username ALL = NOPASSWD : ALL

Marvin Fischer
  • 2,552
  • 3
  • 23
  • 34
siasty
  • 167
  • 1
  • 2
  • 10
0

If you want to use "sudo", the user running your program should be in sudoers group.

Hasan
  • 2,444
  • 3
  • 30
  • 44