TL;DR
Allowing sudo access via SSH keys involves adding your user to the sudoers file, but doing it safely. This guide shows you how using visudo and configuring NOPASSWD for specific commands if needed.
How To Allow Sudo Access With SSH Keys
- Understand the Risks
- Edit the
sudoersfile safely - Add your user to the sudo group (if applicable)
- Add a specific user
- Restrict sudo access to specific commands
- Configure NOPASSWD for specific commands (optional)
- Save and Exit
visudo - Test your sudo access
Granting sudo access gives a user significant power. Ensure you trust the key owner before proceeding. Compromised keys can lead to full system compromise.
Never edit the sudoers file directly with a text editor! Always use visudo. This tool provides syntax checking and prevents multiple simultaneous edits, reducing the risk of corruption.
sudo visudo
On some systems (like Debian/Ubuntu), users in the sudo group automatically have sudo access. Check if you’re already a member:
groups $USER
If not, add yourself:
sudo usermod -aG sudo $USER
You may need to log out and back in for the group change to take effect.
If you don’t want to use groups, add your username directly to the sudoers file. Find a line similar to this:
root ALL=(ALL:ALL) ALL
Add a new line below it for your user (replace your_username with your actual username):
your_username ALL=(ALL:ALL) ALL
For increased security, limit the commands a user can run with sudo. For example, to allow only restarting Apache:
your_username ALL=(ALL:ALL) /usr/sbin/service apache2 restart
If you want a user to run certain commands with sudo without being prompted for a password, add NOPASSWD: before the command. For example:
your_username ALL=(ALL:ALL) NOPASSWD: /usr/sbin/service apache2 restart
Warning: Use NOPASSWD: sparingly, as it reduces security.
Press Ctrl+X, then Y to save the changes. visudo will check for syntax errors before saving.
Log in via SSH as the user you configured and try running a command with sudo:
sudo whoami
If everything is set up correctly, it should execute the command without errors (or prompt for a password if NOPASSWD wasn’t used).