andybeak
1/20/2017 - 4:34 PM

Create a new user

Create a new user

#!/bin/bash

if [ "$EUID" -ne 0 ]
  then echo "Please run as root"
  exit
fi

if [ $# -eq 0 ]
  then
    echo "You have to supply the name of the user as a parameter"
    exit
fi

if [ -f .profile ];
then
	useradd -d /home/$1 -m $1
	# create ssh directory and key
	mkdir /home/$1/.ssh
	touch /home/$1/.ssh/authorized_keys
	chown -R $1:$1 /home/$1
	chmod 700 /home/$1/.ssh
	chmod 600 /home/$1/.ssh/authorized_keys
	# copy bash profile and set bash as their shell
	cp .profile /home/$1
	cp .bashrc /home/$1
	sed -i "s|/home/$1:|/home/$1:/bin/bash|" /etc/passwd
	# add them to sudoers
	usermod -aG sudo $1
	touch /etc/sudoers.d/$1
	echo "$1 ALL=(ALL) NOPASSWD:ALL" > /etc/sudoers.d/$1
	chmod 440 /etc/sudoers.d/$1
	# make sure that the permissions are right so that you don't bork your sudo
	chown root:root -R /etc/sudoers.d
	chmod 755 /etc/sudoers.d
	chmod 440 /etc/sudoers.d/*
	# use sudo even though we're root because this will throw a warning if there is a problem
	sudo echo "Created.  Remember to add the authorized key!"
else
	echo "Run this in an existing user directory"
fi