Home > OS >  How can I make my bash script create an ssh key pair for a given user
How can I make my bash script create an ssh key pair for a given user

Time:08-27

I am new to bash scripting. I wrote a script that can create groups and users which works just fine, but my challenge now is how do I make the script create an ssh key pair for a particular user. From my script, it stopped working immediately after you switch to that user and it doesn't proceed to create the ssh key pair.

Below is my script.

    for group in admin support engineering
    do
            sudo groupadd $group
            sudo useradd -m -s /bin/bash achebeh_${group}
    done
    sudo passwd achebeh_admin
    sudo su achebeh_admin
    ssh-keygen -t rsa

So please how can I go about creating an ssh pair for the achebeh_admin user using this script. I am open to learn. Please this is my firs script after following a tutorial course.

CodePudding user response:

@Achebe-peter If I got your requirements correctly from your short description, this will do the job for you.

Note:

  • Try this script in a test environment at your own risk!
  • This script best performs assuming that you don't have configured users and related files
#!/bin/bash
### Configuration Parameters Start ###
## The username that doesn't exist and you want to create.
user_name_prefix='testuser'

## The groups array that doesn't exist and you want to create and assign them to your user.
groups=(testadmin testsupport testengineering)

## SSH-key lenght
ssh_key_lenght='2048'
### Configuration Parameters End ###


for group in ${groups[@]} ;do
  # Set username containing the prefix and group name
  user="${user_name_prefix}_${group}"

  # create such user if not exist
  getent passwd ${user} &>/dev/null
  if [ "$?" -ne 0 ] ;then
    sudo useradd -m -s /bin/bash "${user}"

    echo -e "\nType password for: ${user}"
    sudo passwd ${user}
  fi

  # Create '.ssh' directory in user's home directory
  if ! [ -d /home/${user}/.ssh ] ;then
    sudo mkdir /home/${user}/.ssh
  fi

  # Generate ssh-key pair and move them to correspondig user's '.ssh/' dir.
  ssh_file_name="./${user}_ssh"
  (
  echo "${ssh_file_name}"
  echo ""
  echo "" 
  ) | ssh-keygen -t rsa -b ${ssh_key_lenght}

  sudo mv -i "${ssh_file_name}" "${ssh_file_name}.pub" /home/${user}/.ssh/
  sudo chown ${user}:${user} /home/${user}

  # Create the groups (if does not exist)
  getent group ${group} &>/dev/null
  if [ "$?" -ne 0 ] ;then
    sudo groupadd ${group}
  fi

  # Assign relevant group to the new user
  sudo usermod -aG ${group} ${user}
done

exit 0
Tested in
GNU bash, version 5.0.17(1)-release (x86_64-pc-linux-gnu)
Copyright (C) 2019 Free Software Foundation, Inc.
License GPLv3 : GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

PS. Please vote up my answer and mark it as the correct answer if it satisfies your requirements.

  • Related