Use Public Key to prevent sudo password prompt

  1. First of all we need to install the pam library
apt-get update && apt-get install libpam-ssh-agent-auth

2.   Then edit /etc/pam.d/sudo and add following line directly after #%PAM-1.0

auth sufficient pam_ssh_agent_auth.so file=/etc/security/authorized_keys

3.   Add your ssh public key to /etc/security/authorized_keys

4.   Then add following line after other defaults in /etc/sudoers (use visudo)

Defaults env_keep += SSH_AUTH_SOCK

5.   Execute following command to enable automatic launch of assh-agent on startup

echo "ssh-add" >> ~/.bash_profile

6.   Voila! You can now use passwordless sudo on your server if you authenticated via an ssh key.

OPTIONAL:

7.   For better security you can use an encrypted ssh private key. This only requires one password if loaded into ssh-agent.

You can follow this guide, if you want to automatically decrypt several ssh-keys with a master-password in keepass:

https://techgoat.net/index.php?id=109

Sources:

https://wiki.gentoo.org/wiki/Pam_ssh_agent_auth

How to allow authentication with `sudo` using an alternate password?
I have been given a long password by my company for my Ubuntu system. This password is cumbersome to enter when authenticating with sudo repeatedly. Can I authenticate with sudo using a password ...
Setting up PAM SSH agent authentication for sudo login
For security reasons it is good to use ssh keys. As long you only have one user everything is fine. If you want control who is able to execute as sudo this solutions shines, cause of it’s flexibility.
libpam-ssh-agent-auth : Bionic (18.04) : Ubuntu
pam_ssh_agent_auth is a PAM module which permits PAM authentication via your keyring in a forwarded ssh-agent. . This module can be used to provide authentication for anything run locally that supports PAM. It was written specifically with the intention of permitting authentication for sudo wi…

https://techgoat.net/index.php?id=109