Sunday, February 14, 2016

Adding a linux user by shell scripting

#!/bin/bash

if [ $(id -u) -eq 0 ]; then #checking you either root or normal user
    echo -n " write the username: "
    read  username          #Taking username from keyboard
    echo -n " write the Password: "
    read -s  password       #Taking password from keyboard
  
    #check the username in passwd file if exist and printing value to null
    grep "$username" /etc/passwd >/dev/null
  
    if [ $? -eq 0 ]; then
        echo "***************************"
        echo " $username already exist  *"
        echo "***************************"
        exit 1
    else
        pass=$(perl -e 'print crypt($ARGV[0], "password")' $password) #encrypting password
        useradd -m -p $pass $username
        [ $? -eq 0 ] && echo "User has been added to system!" || echo "Failed to add a user!"
    fi
else
    echo ""
    echo "**********************************************************"
    echo " U are not root. Only root may add a user to the system  *"
    echo "**********************************************************"
    exit 2
fi

2 comments: