Thursday, May 18, 2017

Create Linux User with ssh key



If you are not using configuration automation tools like Puppet or Chef on simple Linux environment, script below will definitely simplify your Linux user creation process, especially when you have more than 10 new users to create in a row.

It will also take care of ssh key insertion to user profile, the most common issues I often encounter, during user creation with ssh key, was mixing up authorized_keys file permission and ownership between root and actual user itself since some account switch is needed.

I hope the script below would help some of you out there, making your daily sysadmin jobs simpler and more fun.



#/bin/bash

while getopts u:c:s: option
do
        case "${option}"
        in
                u) USER=${OPTARG};;
                c) CERT=${OPTARG};;
                s) SUDO=${OPTARG};;
        esac
done

echo "$CERT";
adduser $USER;

if [ "$SUDO" == "y" ]
then
        touch /etc/sudoers.d/$USER;
        echo "$USER ALL=(ALL:ALL) ALL" > /etc/sudoers.d/$USER;
        echo User added to root;
fi

su -c  'mkdir -p ~/.ssh && touch ~/.ssh/authorized_keys && chmod 700  ~/.ssh && chmod 600  ~/.ssh/authorized_keys' - $USER;
echo  "$CERT" > /home/$USER/.ssh/authorized_keys


passwd $USER;



Sample command
./adduser.sh -u myuser -s y  -c 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDpjky6uTgUa9eRdG/hOxjQvWDbHzw/AVVsvJmMYxwwaLBgUtESRNXEMiF56qIxxxxxxxxxxxxlzbuOLmCrM29mlyujKdqkbr8z75aWYzhT+UIma5BuEX6kLyo9LYMm4RXGsbbnfHYrvTJo1FAnzRL/LYH8ewtmvzVTauHP/k1jYbp0Q3jQgf7p1ZDssAf5vDe1sMLwaXMGUNqNKCwjjePxOxIWzQksOCjHv/ myuser@gmail.com'


Note:
- Avoid creating user with the character dot ".", else system will fail to pickup sudoers file setting.
- Script above only tested on Redhat, Amazon Linux, CentOS but not on Debian platform.