Skip to content

Instantly share code, notes, and snippets.

@josemarcosrf
Created October 8, 2019 11:39
Show Gist options
  • Select an option

  • Save josemarcosrf/8155e027693ced580234e97e89bd8c77 to your computer and use it in GitHub Desktop.

Select an option

Save josemarcosrf/8155e027693ced580234e97e89bd8c77 to your computer and use it in GitHub Desktop.

Revisions

  1. @jmrf jmrf created this gist Oct 8, 2019.
    70 changes: 70 additions & 0 deletions create_user.sh
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,70 @@
    #!/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"