0

I can ssh into a remote EC2 instance with ec2-user and the keypair in the EC2 account with root(sudo) privileges.

How can I manually create another non-ec2-user user account, add an SSH key, and add sudo permissions to that user?

fatal_error
  • 1,102
  • 1
  • 11
  • 18

1 Answers1

0

Create the user account

First, create the user account using the standard Linux/UNIX useradd command:

NEWUSER='newusername'
SSHPUBKEY='ssh-ed25519 AAAA..xyz jamieson@desktop'
sudo useradd -m $NEWUSER

Add the SSH public key to that user's authorized_keys file

It's critical to chown the directory back to the user, or the SSH daemon will reject the file that's owned by root and not $NEWUSER. (Another way to do this is to use ssh-copy-id, but this way can be done in the same login session.)

sudo mkdir /home/$NEWUSER/.ssh/
echo "$SSHPUBKEY" | sudo tee -a /home/$NEWUSER/.ssh/authorized_keys >/dev/null
sudo chown -R $NEWUSER:$NEWUSER /home/$NEWUSER/.ssh

Set up sudo permissions for that user

This uses the standard /etc/sudoers.d directory (found in all major distributions) to add sudo permissions with an "ALL" role to the user account.

echo "$NEWUSER ALL=(ALL) NOPASSWD: ALL" | sudo tee "/etc/sudoers.d/$NEWUSER" >/dev/null

(Disclaimer: I wrote the first release of a tool that automates this at Userify.)

fatal_error
  • 1,102
  • 1
  • 11
  • 18
  • See also https://serverfault.com/a/218995/133137 for some information on why `chown` is needed. Fortunately, just creating the file like this and then `chown`ing it is sufficient. – fatal_error Mar 19 '19 at 05:53