Return to Snippet

Revision: 64294
at July 20, 2013 05:15 by derbenni

Initial Code
# Script to add a user to Linux system
if [ $(id -u) -eq 0 ]; then
	read -p "Enter username : " username
	read -s -p "Enter password : " password
	egrep "^$username" /etc/passwd >/dev/null
	if [ $? -eq 0 ]; then
		echo "$username exists!"
		exit 1
		echo "Creating user"
		pass=$(perl -e 'print crypt($ARGV[0], "password")' $password)
		useradd -m -p $pass $username
		[ $? -eq 0 ] && echo "User has been added to system!" || echo "Failed to add a user!"

		echo "Creating directory public_html"
		mkdir /var/www/$username
		ln -s /var/www/$username /home/$username/public_html
		chown -R $username /var/www/$username
		chgrp -R $username /var/www/$username

		echo "Creating vHost for " $username ".local"
		cat <<EOF > /etc/apache2/sites-available/$domain
<VirtualHost *:80>
        ServerAdmin $username@localhost
        DocumentRoot /var/www/$username
        ServerName $domain

        <Directory />
		Options FollowSymLinks
		AllowOverride None
	<Directory /var/www/$username>
		Options Indexes FollowSymLinks MultiViews
		AllowOverride None
		Order allow,deny
		allow from all

        ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
        <Directory "/usr/lib/cgi-bin">
                AllowOverride None
                Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
                Order allow,deny
                Allow from all

        ErrorLog \${APACHE_LOG_DIR}/$domain.error.log
        # Possible values include: debug, info, notice, warn, error, crit, alert, emerg.
        LogLevel warn
        CustomLog \${APACHE_LOG_DIR}/$domain.access.log combined

	Alias /doc/ "/usr/share/doc/"
	<Directory "/usr/share/doc/">
		Options Indexes MultiViews FollowSymLinks
		AllowOverride None
		Order deny,allow
		Deny from all
		Allow from ::1/128

	echo "Enabling site"
	a2ensite $domain

	echo "Creating database and user"
	echo "CREATE DATABASE " $username "; GRANT ALL ON " $username ".* TO " $username "@localhost IDENTIFIED BY '" $password "';" | mysql --user=root --password=

	echo "Adding " $domain " to /etc/hosts"
	echo "	" $domain >> /etc/hosts

	echo "Restarting Apache"
	/etc/init.d/apache2 reload

	echo "Only root may add a user to the system"
	exit 2

Initial URL

Initial Description
With this script a new user gets created and gets his own VirtualHost and database. The username is used for building the domain, so the username "test" leads to the domain test.local.

The password for the MySQL account used for creating the database has to be filled in for the script to work. Also the script has to be run by root.

Initial Title
Create vHost with user and MySQL database

Initial Tags
mysql, Bash, unix, linux

Initial Language