Skip to main content

C# Dealing with Sudo

Sudo presents some challenges when scripting command line work.

Sudo was intended ONLY to be presented for interactive user sessions, to make sure a user is aware of the risk of the command being executed.
But instead. Even a scripted CLI call from Python or C# will be presented with a sudo challenge, despite the actual intent of sudo.

So. We have a few options to deal with this:

a. We can add the user account to the sudoers group, so any CLI call will not be presented with a sudo challenge.

b. We can write fancy stream handling to imitate the standard input of a PTY, so we can inject a sudo response IF asked.

c. We can leverage the -S argument of sudo, and pipe the user's password as standard input, via echo.

Piping via Echo

Sudo has a switch '-S' which tells it to accept the user's password via standard input:

sudo -S <command>

We can pipe a password into the above command with Echo, like this:

echo "your_password" | sudo -S <command>

But, two subtleties are still to be dealt with.

First, Bash shell saves command history, so the echo command will expose our password in history.
So, we must tell bash to not save history for our command, like this:

export HISTIGNORE='*sudo -S*' && echo "your_password" | sudo -S <command>

The above takes care of our password not being recorded to command history.

Second. Sudo is not consistent in its ask for a password. Specifically, it will look in its cache for a user's password, and use that if available. So, we must tell it to ignore any cached credentials, by adding the '-k' switch:

sudo -S -k <command>

Now, the whole command string becomes:

export HISTIGNORE='*sudo -S*' && echo "your_password" | sudo -S -k <command>

And, we can safely use the above composite command as a wrapper around any sudo command we need to perform through a python or C# CLI wrapper.

References:

https://superuser.com/questions/67765/sudo-with-password-in-one-command-line