Tan Viet
Tan Viet

Reputation: 2113

How can run Linux command with sudo from dotnetcore?

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

Upvotes: 1

Views: 2196

Answers (2)

siasty
siasty

Reputation: 177

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

Upvotes: 1

Hasan
Hasan

Reputation: 2552

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

Upvotes: 0

Related Questions