Link Unix machines to AD using Quest Autentication Services. Install it using expect.

This next script uses the library introduced on a previous post =>

This script was launched at the end of the installation of all the workstations on the company.
It configures the linux, or MAC , to be part of an Active Directory, which allows the administrator to manage the root passwords, what runs at boot, and even the desktop background.

http://www.quest.com/authentication-services/

However, the installation and configuration was slow and wanted to be interactive, so in this case we used expect to automate the human interaction.

The first script is the bash that was launched after the pre-seed job, then comes the expect (which is launched from inside the bash).

#!/bin/bash -x

# Script de instalacion de QAS en un desktop
# El script llama a fbm_qas_install.expect, donde se ejecutan instrucciones expect. 

# Las salidas por pantalla, se redirigen al fichero output.expect.o
# Los errores se redirigen al fichero output.expect.e # :TODO:01/14/2011 10:32:18 AM CET:: unificar output
exec 1>./output.expect.o
exec 2>./output.expect.e

# Definicion de variables.
USERNAME="username_only_allowed_to_add_machines_to_AD"
PASS="pass for that user"
SERVERIP="xx.yy.tt.rr ip of our repository with all the scripts , also the library. "
SERVERPATH="scripts"
MASTERURL="http://$SERVERIP/$SERVERPATH"

# Funcion para instalar paquete 'smbfs'.
installsmbfs(){
	 echo "Installing smbfs"
	 apt-get update
	 apt-get -y upgrade
	 apt-get -y autoremove
	 apt-get -y install smbfs 
}

 # :TODO:01/14/2011 10:32:34 AM CET:: smbfs is not necessary 
# Comprueba si el paquete 'smbfs' esta instalado en el sistema. Si no lo esta, ejecuta la funcion 
# llamada 'installsmbfs'.
dpkg-query -l 'smbfs'
[ "$?" -eq  "0" ] && echo "smfs is already installded. Keep going" || installsmbfs

 # :TODO:01/14/2011 10:32:34 AM CET:: smbfs is not necessary 
# Comprueba si el paquete 'smbfs' esta instalado en el sistema. Si lo esta, no hace nada.
dpkg-query -l 'smbfs'
[ "$?" -eq  "0" ] && echo "smfs has been installed. Keep going" || die " smfs can not be installed " 

# Modifica un parametro del fichero /etc/ssh/sshd_config y reinicia el servicio sshd
sed -i 's/ChallengeResponseAuthentication no/ChallengeResponseAuthentication yes/g' /etc/ssh/sshd_config
/etc/init.d/ssh reload
 # :TODO:01/14/2011 10:32:58 AM CET:: check if directory already existes , also check if files already exist
# Descarga ficheros vas.conf y vgp.conf en sus rutas correspondientes
mkdir -p /etc/opt/quest/vas
mkdir -p /etc/opt/quest/vgp
wget $MASTERURL/etc/opt/quest/vas/vas.conf  -O /etc/opt/quest/vas/vas.conf
wget $MASTERURL/etc/opt/quest/vgp/vgp.conf  -O /etc/opt/quest/vgp/vgp.conf

# Modifica el template vas.conf. Escribe el nombre del PC
sed  -i "s/%%HOSTNAME%%/`hostname`/g" /etc/opt/quest/vas/vas.conf

[ -d /home/sysop/fs ] && echo "fs exists" || echo "fs does not exist"
[ -d /home/sysop/fs/QAS_4_0_1_22 ] && echo "QAS dir  exists" || echo "QAS dir  does not exist"

cd /home/sysop
 # :TODO:01/14/2011 10:33:33 AM CET:: this should be done on /tmp
wget $MASTERURL/src/QAS_4.tgz
tar xvzf QAS_4.tgz

cd /home/sysop/QAS_4_0_1_22
./install.sh -q vasclnt
./install.sh -q vasgp
/opt/quest/bin/vastool configure pam common-password

apt-get -y install expect
############################# install qas
tempscript="fbm_qas_install.expect"
if [ ! -f ./$tempscript ]
then
        wget $MASTERURL/bin/$tempscript
fi
chmod +x $tempscript
./$tempscript $USERNAME $PASS

exit 0
#!/usr/bin/expect -f

# Script de expect. Script pide pasar parametros en la instalacion de l aaplicacion QAS
# Con expect, esos parametros se pasan de forma automatica.
#echo "dentro expect"


# Se definen la svariables USERNAME y PASS con el valor de los parametros que recibe el script.
set USERNAME [lindex $argv 0]
set PASS [lindex $argv 1]

# ejecutar el fichero ./install.sh del instalador de QAS
spawn /opt/quest/bin/vastool -u $USERNAME join corp.barcelonamedia.org
# contestar las preguntas de la instalacion de QAS de forma desatendida
sleep 1
expect "CORP.ACTIVEDIRECTORYDOMAIN.ORG:*" 
sleep 1
send "$PASS\r"
sleep 60

The scripts that become functions, and the functions that belong to a library .

Long ago, when I had the chance to build by myself a set of scripts that performed certain operations I ended up with a nice set of small things.

I would like to share, but it needs some explanation.

This library, group of tools, they do nothing by themselves, their only serve a single purpose which is “To standardize” .
At that time I was a “one man army”, I built stuff by myself, for myself and to myself, but then I realized that after me would come someone else, with different styles, different habits and so on,..

Since I needed to change as less code possible this library can be sourced and its functions called many times, they become read only , or they are atomic, so nothing has be worried about using its functions several times in a row.

#!/bin/bash
# Marcs library 
#TODO
# there are two lower case converters
# funcion to download all the scripts at once
# funcion to clean up all the scripts

# set variables 
declare -r TRUE=0
declare -r FALSE=1
declare -r PASSWD_FILE=/etc/passwd
declare -r RED='\033[0;41;30m'
declare -r STD='\033[0;0;39m'
declare -r CYAN='\e[1;37;44m'
declare -r TMPDIR='/tmp/'
##################################################################
# Purpose: Converts a string to lower case
# Arguments:
#   $1 -> String to convert to lower case
##################################################################
function to_lower() 
{
    local str="$@"
    local output     
    output=$(tr '[A-Z]' '[a-z]'<<<"${str}")
    echo $output
}
##################################################################
# Purpose: Display an error message and die
# Arguments:
#   $1 -> Message
#   $2 -> Exit status (optional)
##################################################################
function die() 
{
    local m="$1"	# message
    local e=${2-1}	# default exit status 1
    echo "$m" 
    exit $e
}
##################################################################
# Purpose: Return true if script is executed by the root user
# Arguments: none
# Return: True or False
##################################################################
function is_root() 
{
   [ $(id -u) -eq 0 ] && return $TRUE || return $FALSE
}
##################################################################
# Purpose: Return true $user exits in /etc/passwd
# Arguments: $1 (username) -> Username to check in /etc/passwd
# Return: True or False
##################################################################
function is_user_exits() 
{
    local u="$1"
    grep -q "^${u}" $PASSWD_FILE && return $TRUE || return $FALSE
}



##################################################################
# Purpose: Inform the user that this functions is not implemented
# Arguments: No arguments 
# Return: No returns
##################################################################
function notImplemented()
{
	 echo "This functions is not implemented yet."
	 echo "Press any Key to continue or press Ctrl-C."
	 read x
}
##################################################################
# Purpose: Converts a string to lower case
# Arguments:
#   $1 -> String to convert to lower case
##################################################################
lowercase(){
	echo "$1" | sed "y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/"
}
##################################################################
# Purpose: Recover important information 
# Arguments: If $1 == "debug" then output for each var will be printed
# Return: TRUE is first time execution. FALSE if already executed
# Read Only variables set:
#	OS
#	DIST
#	DistroBasedOn
#	PSUEDONAME
#	REV
#	KERNEL
#	MACH
##################################################################
shootProfile(){
	 # This funcion creates readonly variables, if one of them has been set before it will crash
	 # check that all variables are unset.
	 [ -n "${OS+x}" ] && [ -n "${DIST+x}" ] && [ -n "${DistroBasedOn+x}" ] && [ -n "${PSUEDONAME+x}" ] && [ -n "${REV+x}" ] && [ -n "${KERNEL+x}" ] && [ -n "${MACH+x}" ] && echo " !!! shootProfile was called before. The variables are already available" &&  return $FALSE

	 OS=`lowercase \`uname\``
	 KERNEL=`uname -r`
	 MACH=`uname -m`

	 if [ "{$OS}" == "windowsnt" ]; then
		  OS=windows
	 elif [ "{$OS}" == "darwin" ]; then
		  OS=mac
	 else
		  OS=`uname`
		  if [ "${OS}" = "SunOS" ] ; then
				OS=Solaris
				ARCH=`uname -p`
				OSSTR="${OS} ${REV}(${ARCH} `uname -v`)"
			elif [ "${OS}" = "AIX" ] ; then
				OSSTR="${OS} `oslevel` (`oslevel -r`)"
			elif [ "${OS}" = "Linux" ] ; then
				if [ -f /etc/redhat-release ] ; then
					 DistroBasedOn='RedHat'
					 DIST=`cat /etc/redhat-release |sed s/\ release.*//`
					 PSUEDONAME=`cat /etc/redhat-release | sed s/.*\(// | sed s/\)//`
					 REV=`cat /etc/redhat-release | sed s/.*release\ // | sed s/\ .*//`
				elif [ -f /etc/SuSE-release ] ; then
					 DistroBasedOn='SuSe'
					 PSUEDONAME=`cat /etc/SuSE-release | tr "\n" ' '| sed s/VERSION.*//`
					 REV=`cat /etc/SuSE-release | tr "\n" ' ' | sed s/.*=\ //`
				elif [ -f /etc/mandrake-release ] ; then
					 DistroBasedOn='Mandrake'
					 PSUEDONAME=`cat /etc/mandrake-release | sed s/.*\(// | sed s/\)//`
					 REV=`cat /etc/mandrake-release | sed s/.*release\ // | sed s/\ .*//`
				 elif [ -f /etc/debian_version ] ; then
					 DistroBasedOn='Debian'
					 DIST=`cat /etc/lsb-release | grep '^DISTRIB_ID' | awk -F= '{ print $2 }'`
					 PSUEDONAME=`cat /etc/lsb-release | grep '^DISTRIB_CODENAME' | awk -F= '{ print $2 }'`
					 REV=`cat /etc/lsb-release | grep '^DISTRIB_RELEASE' | awk -F= '{ print $2 }'`
				 fi
				 if [ -f /etc/UnitedLinux-release ] ; then
					 DIST="${DIST}[`cat /etc/UnitedLinux-release | tr "\n" ' ' | sed s/VERSION.*//`]"
				  fi
				OS=`lowercase $OS`
				DistroBasedOn=`lowercase $DistroBasedOn`
				readonly OS
				readonly DIST
				readonly DistroBasedOn
				readonly PSUEDONAME
				readonly REV
				readonly KERNEL
				readonly MACH
		  fi

	 fi
	local debug=${1:-nodebug}
	 if [[ $debug = "debug" ]]; then
				echo $OS
				echo $DIST
				echo $DistroBasedOn
				echo $PSUEDONAME
				echo $REV
				echo $KERNEL
				echo $MACH
	 fi
	 return $TRUE
}
##################################################################
# Purpose: Make sure package on $1 is installed 
# Arguments:
#   $@ -> Packages wich should be installed
##################################################################
installPkg()
{
	 [ -n "${DistroBasedOn-x}" ] && shootProfile
	for i in $@
	do
		echo -n "Installing $i on $DistroBasedOn."
		case $DistroBasedOn in
			Debian | debian )
				 apt-get -y install $i
				 ;;
			SuSe | suse )
				 zypper install $i
				 ;;
			Mandrake | mandrake )
				 echo "do not know how to install $i package on mandrake "
				 ;;
			RedHat | redhat )
				 yum -y install $i
				 ;;
			*)
				 echo "\$DistroBasedOn variable has not a valid value. Value : ||$DistroBasedOn||"
				 ;;
		esac
	done
return 0
}
##################################################################
# Purpose: Compare hostname
# Arguments: 
#	$1 => string 
# Return : TRUE if $1 = `hostname` false otherwhise.
##################################################################
hostnameGet(){
	 [[ "`hostname`" = "$1" ]] && return $TRUE || return $FALSE
}
##################################################################
# Purpose: Return TRUE if $1 is confirmed, or keypresed
# Arguments: 
#	$1 => string 
# Return : TRUE if $1 user presses the key.
##################################################################
confirm(){
	 read -sn 1 -p "$1 [y/N]? "
	 [[ $REPLY = [Yy] ]] && return $TRUE|| return $FALSE
}

#===  FUNCTION  ================================================================
#          NAME:  downloadAndExec
#   DESCRIPTION:  downloads and launches a script
#    PARAMETERS:  $1 = script name
#       RETURNS:  TRUE if OK
#===============================================================================

downloadAndExec ()
{
	scriptname=$1
	workdir="/tmp"
	workscript=$workdir/$scriptname
	[ -f $workscript ] && rm $workscript
	wget $MASTERURL/bin/$scriptname -O $workscript
	chmod +x $workscript
	$workscript
	[[ $? -eq 0 ]] && rm $workscript && return $TRUE || return $FALSE

}	# ----------  end of function downloadAndExec  ----------

return 0

Last.fm desde shell

Last.fm se tiene intención de hacer pagar ciertos servicios a alguna gente. link. De momento lo han pospuesto. Aún así esto es útil cuando estas algo justito de ram y lanzar firefox relentiza todo el sistema.

Para aquellos que quieran probarlo hay programita usar last.fm desde shell.

Continue reading “Last.fm desde shell”