Created
October 8, 2019 11:39
-
-
Save josemarcosrf/8155e027693ced580234e97e89bd8c77 to your computer and use it in GitHub Desktop.
Create a new user in UBuntu 18.04 and enable remote SSH login
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
say() { | |
echo "$@" | sed \ | |
-e "s/\(\(@\(red\|green\|yellow\|blue\|magenta\|cyan\|white\|reset\|b\|u\)\)\+\)[[]\{2\}\(.*\)[]]\{2\}/\1\4@reset/g" \ | |
-e "s/@red/$(tput setaf 1)/g" \ | |
-e "s/@green/$(tput setaf 2)/g" \ | |
-e "s/@yellow/$(tput setaf 3)/g" \ | |
-e "s/@blue/$(tput setaf 4)/g" \ | |
-e "s/@magenta/$(tput setaf 5)/g" \ | |
-e "s/@cyan/$(tput setaf 6)/g" \ | |
-e "s/@white/$(tput setaf 7)/g" \ | |
-e "s/@reset/$(tput sgr0)/g" \ | |
-e "s/@b/$(tput bold)/g" \ | |
-e "s/@u/$(tput sgr 0 1)/g" | |
} | |
create_user () { | |
user=$1 | |
if [ -z "$user" ] | |
then | |
say @red[["You need to pass a user name to create the new user"]] | |
exit 1; | |
fi | |
say @green[["Creating user '$user'"]] | |
adduser $user | |
usermod -aG sudo $user | |
} | |
install_ssh_key () { | |
user=$1 | |
key=$2 | |
if [ -z "$user" ] | |
then | |
say @red[["You need to pass a user name to whom you want to add a SSH key for"]] | |
exit 1; | |
fi | |
if [ -z "$key" ] | |
then | |
say @red[["You need to pass the public key content"]] | |
exit 1; | |
fi | |
say @green[["Login in as '$user' and creating the 'authorized_keys' file"]] | |
su - $user -c \ | |
"mkdir -p ~/.ssh && \ | |
chmod 700 ~/.ssh && \ | |
echo $key >> ~/.ssh/authorized_keys && \ | |
chmod 600 ~/.ssh/authorized_keys && \ | |
exit" | |
} | |
# read the user name and create user | |
read -p "Enter the new user name: " usr | |
echo | |
create_user $usr | |
# read SSH key contents and add to authorized_keys | |
read -s -p "Enter the PUBLIC SSH key to login: " key | |
echo | |
install_ssh_key $usr "$key" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment