Recursive file counter in bash

Most of the scripts presented in this journal have been created while learning bash and having nothing much to do…

I think its usual to get crazy ideas and work trying to implement them, especially while learning any type of coding.  This  ‘File Counter’ script came as such a  crazy idea. It was working at the time of its creation, but have not checked it recently.. should work..

This script counts the entire number of files irrespective the folders under the main directory you specify for this script to work on. ie.. It recursively  counts the files under a directory tree.

#!/bin/bash

#  Counts the number of files recursively inside a directory    #
#
echo ; clear
echo -e "Please enter the directory location where you want the files to be counted...\n" ; echo

read dir ; echo ;  if [ ! -d $dir ] ; then echo -e "The location you specified doesn't exist.\n" ; exit 0;
else cd $dir ; echo -e "Please wait for the files to be counted.....\n" ; echo ; fi

X=`ls -l | wc -l`
Y=`ls -l | grep ^d | awk '{print $9}'`
B=`ls -l $Y | awk '{print $9}' | grep . | wc -l `
A=`expr $X + $B`

echo -e "There are a total of $A files inside the directory $dir...\n"

C=`ls -Rl | grep -v ./ | grep -v total | grep . | awk '{print $8}'`

echo -e "Do you want to scan the directory for the file types?\n"
echo -e "Y/N\n" ; read choice;
if [ $choice = Y ] ;
then cd $dir ; file $C | awk '{print $1,"=======>>", $2}' > $HOME/Filetype.txt;echo -e "Output saved in file Filetype.txt.\n"
elif [ $choice = N ] ; then echo -e "Thankyou $USER, Take care....\n"
else echo ; echo -e "Invalid choice buddy...\n" ; echo -e "Exiting.....Bye..\n" ;  fi

 

Bootloader checker

A bash code snippet that helps to check if the installed bootloader is Grub or LILO.

#!/bin/bash

A=`mount | awk '{print $1}' | grep -n /dev/ | grep "1:" | cut -f2 -d ":" | cut -c 1-8`
B=`mount | awk '{print $1}' | grep -n /dev/ | grep "1:" | cut -f2 -d ":"`

echo ; echo -e " / mounted on $B \n";
dd if=$A bs=512 count=1 2>&1 | grep GRUB > /dev/null;
if [ $? = 0 ] ; then echo -e "The installed bootloader is GRUB.\n" ; fi

dd if=$A bs=512 count=1 2>&1 | grep LILO > /dev/null;
if [ $? = 0 ] ; then echo -e "The installed bootloader is LILO.\n" ; fi

Creating a SWAP space in Linux

Adding Swap Space:

Sometimes it is necessary to add more swap space after installation. For example, you may upgrade the amount of RAM in your system from 64 MB to 128 MB, but there is only 128 MB of swap space. It might be advantageous to increase the amount of swap space to 256 MB if you perform memory-intense operations or run applications that require a large amount of memory.

You have two options: add a swap partition or add a swap file. It is recommended that you add a swap partition, but sometimes that is not easy if you do not have any free space available.

To add a swap partition (assuming /dev/hdb2 is the swap partition you want to add):

1)  The hard drive can not be in use (partitions can not be mounted, and swap space can not be enabled). The easiest way to achieve this it to boot your system in rescue mode. Refer to Chapter 8 for instructions on booting into rescue mode. When prompted to mount the filesystem, select Skip. Alternately, if the drive does not contain any partitions in use, you can unmount them and turn off all the swap space on the hard drive with the swapoff command.

2)  Create the swap partition using parted or fdisk. Using parted is easier than fdisk; thus, only parted will be explained. To create a swap partition with ‘parted:’. At a shell prompt as root, type the command parted /dev/hdb, where /dev/hdb is the device name for the hard drive with free space. At the (parted) prompt, type print to view the existing partitions and the amount of free space. The start and end values are in megabytes. Determine how much free space is on the hard drive and how much you want to allocate for a new swap partition. At the (parted) prompt, type mkpartfs part-type linux-swap start end, where part-type is one of primary, extended, or logical, start is the starting point of the partition, and end is the end point of the partition.

            Warning     Warning
_________________________

Changes take place immediately; be careful when you type.

Exit parted by typing quit.

3) Now that you have the swap partition, use the command mkswap to setup the swap partition. At a shell prompt as root, type the following:

# mkswap /dev/hdb2

4) To enable the swap partition immediately, type the following command:

# swapon /dev/hdb2

5) To enable it at boot time, edit /etc/fstab to include:

/dev/hdb2               swap                    swap    defaults        0 0

The next time the system boots, it will enable the new swap partition.

6) After adding the new swap partition and enabling it, make sure it is enabled by viewing the output of the command cat /proc/swaps or free.

To add a swap file:
————————–
1.  Determine the size of the new swap file and multiple by 1024 to determine the block size. For example, the block size of a 64 MB swap file is 65536.

2.  At a shell prompt as root, type the following command with count being equal to the desired block size:

# dd if=/dev/zero of=/swapfile bs=1024 count=65536

3. Setup the swap file with the command:

# mkswap /swapfile

4. To enable the swap file immediately but not automatically at boot time:

# swapon /swapfile

5. To enable it at boot time, edit /etc/fstab to include:

/swapfile               swap                    swap    defaults        0 0

The next time the system boots, it will enable the new swap file.

6. After adding the new swap file and enabling it, make sure it is enabled by viewing the output of the command cat /proc/swaps or free.

Nagios Installation Script

This is a bash script which automates the installation of Nagios. There are more things to do such as setup of service monitoring, but that’s for another time.

#!/bin/bash
DOWNLOAD_LOCATION='/root/Downloads/'
NAGIOS_URL='http://jaist.dl.sourceforge.net/sourceforge/nagios/nagios-2.9.tar.gz'
APACHE_CONF='/etc/httpd/conf/httpd.conf'
NAGIOS_PLUGIN='http://nchc.dl.sourceforge.net/sourceforge/nagiosplug/nagios-plugins-1.4.8.tar.gz'
NAGIOSHOME='/usr/local/nagios'
DATE=`date +%d-%b-%Y`
FILE='/root/Nagios.txt'

#################################
# [1]   Installing nagios       #
#################################
nagios_download () {
clear

if [ `id -u` -ne 0 ];
then
echo -e "You are executing the script as $USER\n"
echo -e "You must be root to execute this script..\n";
echo -e "Sorry...Exiting..\n";exit 111;
else
if [ ! -e /root/Nagios.txt ];
then touch /root/Nagios.txt;
else
mv /root/Nagios.txt /root/Nagios-$DATE.txt;
touch /root/Nagios.txt;
fi

echo -e "            [@@@@@@@@@@@@@@@@@@@@@@@@@ NAGIOS INSTALL SCRIPT @@@@@@@@@@@@@@@@@@@@@@@@@]\n";sleep 1s
echo -e "                                           ...Welcome...\n"|tee -a $FILE;sleep 1s
echo "[Starting the Nagios Installation Process :-]"|tee -a $FILE;
echo "---------------------------------------------"|tee -a $FILE;echo;sleep 1s
fi

if [ ! -e $DOWNLOAD_LOCATION ];
then
echo "$DOWNLOAD_LOCATION does not exist, creating......."|tee -a $FILE;sleep 1s
mkdir -pv $DOWNLOAD_LOCATION;echo
fi

echo "[Downloading the nagios tar-ball to $DOWNLOAD_LOCATION :-]"|tee -a $FILE;
echo "--------------------------------------------------------"|tee -a $FILE;echo;sleep 1s

cd $DOWNLOAD_LOCATION && wget --progress=dot $NAGIOS_URL;echo
echo -e "Extracting the archive....\n"|tee -a $FILE;sleep 1s
cd $DOWNLOAD_LOCATION && tar -zxf nagios*gz && mv nagios*gz Nagios-$DATE.tar.gz;echo
}

nagios_usercheck () {
echo "[Checking the existence of user/group 'nagios' :-]"|tee -a $FILE;
echo "--------------------------------------------------"|tee -a $FILE;

grep -q nagios /etc/group > /dev/null
if [ $? = 0 ];then
echo "Group 'nagios' exist"|tee -a $FILE;
else
echo "Adding group 'nagios'"|tee -a $FILE;
/usr/sbin/groupadd nagios
fi

grep -q nagios /etc/passwd > /dev/null
if [ $? = 0 ];then
echo "User 'nagios' exists"|tee -a $FILE;
else
echo "Adding user 'nagios'"|tee -a $FILE;
/usr/sbin/useradd -d $NAGIOSHOME -g nagios -s /bin/false -m nagios
fi;echo

echo "[Checking the existence of user/group 'nagcmd' :-]"|tee -a $FILE;
echo "--------------------------------------------------"|tee -a $FILE;

grep -q nagcmd /etc/group;
if [ $? = 0 ];then
echo "Group 'nagcmd' exists"|tee -a $FILE;
else
echo "Adding group 'nagcmd'"|tee -a $FILE;
/usr/sbin/groupadd nagcmd;
fi

grep -q nagcmd /etc/passwd;
if [ $? = 0 ];then
echo "User 'nagcmd' exists"|tee -a $FILE;
else
echo "Adding user 'nagcmd'"|tee -a $FILE;
/usr/sbin/useradd -g nagcmd -s /bin/false -m nagcmd;
fi;
echo
}

nagios_previouscheck () {
echo "[Checking for previous installations :-]"|tee -a $FILE
echo "----------------------------------------"|tee -a $FILE;sleep 1s

if [ -d /usr/local/nagios ];
then
echo "Installation directory '/usr/local/nagios/' already exist."|tee -a $FILE
echo "Moving '/usr/local/nagios/' to '/usr/local/Nagios-$DATE.back'"|tee -a $FILE
mv -v /usr/local/nagios /usr/local/Nagios-$DATE.back;echo
echo "Creating the Installation Directory for Nagios [/usr/local/nagios/]"|tee -a $FILE
mkdir -pv /usr/local/nagios;echo
else
echo "Nagios installation not found at the default location of $NAGIOSHOME";
echo "Creating the Installation Directory for Nagios [/usr/local/nagios/]"|tee -a $FILE
mkdir -pv /usr/local/nagios;echo
fi
}

nagios_ownership () {
echo "[Setting appropriate ownership on the installation directory]"|tee -a $FILE
echo "-------------------------------------------------------------"
chown -v nagios.nagios /usr/local/nagios;echo;sleep 1s

echo "[Checking the Web-Server user/group :-]"|tee -a $FILE
echo "---------------------------------------"|tee -a $FILE;sleep 1s

echo "Web-Server User  : `grep "^User" $APACHE_CONF|head -n1|awk '{print $2}'`"|tee -a $FILE
echo "Web-Server Group : `grep "^Group" $APACHE_CONF|head -n1|awk '{print $2}'`"|tee -a $FILE;echo;sleep 1s

echo "[Adding the Web-Server/Nagios user to the 'nagcmd' group]"|tee -a $FILE;
echo "---------------------------------------------------------"
/usr/sbin/usermod -G nagcmd `grep "^User" $APACHE_CONF|head -n1|awk '{print $2}'` && \
echo "Added the user `grep "^User" $APACHE_CONF|head -n1|awk '{print $2}'` to the 'nagcmd' group."|tee -a $FILE
sleep 1s
/usr/sbin/usermod -G nagcmd nagios && echo -e "Added the user 'nagios' to the 'nagcmd' group.\n"|tee -a $FILE;sleep 1s
echo
}

nagios_configure () {
echo "[Starting the Nagios 'configure' script :-]"|tee -a $FILE;
echo "-------------------------------------------"|tee -a $FILE;sleep 4s

cd $DOWNLOAD_LOCATION/nagios* && ./configure --with-command-group=nagcmd && make all && make install && make install-config && make install-init && make install-commandmode
echo
}

#################################
# [2] Installing Nagios Plugins #
#################################

nagios_plugins () {
sleep 4s
echo -e "           [@@@@@@@@@@@@@@@@@@@@@@@@@ NAGIOS PLUGIN SETUP @@@@@@@@@@@@@@@@@@@@@@@@@]\n"|tee -a $FILE;sleep 2s

echo "[Downloading the 'nagios-plugins' tarball :-]"|tee -a $FILE;
echo "---------------------------------------------";sleep 3s
cd $DOWNLOAD_LOCATION && wget --progress=dot $NAGIOS_PLUGIN;echo
echo "[Extracting the plugins archive :-]"|tee -a $FILE;
echo "-----------------------------------";sleep 1s
cd $DOWNLOAD_LOCATION && tar -zxf nagios-plugins*gz && mv nagios-plugins*gz Nagios-plugins-$DATE.tar.gz;echo
echo "[Configuring and compiling nagios-plugins :-]"|tee -a $FILE;
echo "---------------------------------------------"|tee -a $FILE;sleep 1s
cd $DOWNLOAD_LOCATION && cd nagios-plugins* && ./configure && make && make install && echo && echo -e "[Nagios Plugin Setup Finished.]\n"
}
echo;echo;sleep 3s

#################################
# [3]  Configuring Nagios       #
#################################
nagios_conf_files () {
echo "[Creating the minimal configuration files :-]";
echo "---------------------------------------------";sleep 2s
cp -apv $NAGIOSHOME/etc/nagios.cfg-sample $NAGIOSHOME/etc/nagios.cfg
cp -apv $NAGIOSHOME/etc/commands.cfg-sample $NAGIOSHOME/etc/commands.cfg
cp -apv $NAGIOSHOME/etc/resource.cfg-sample $NAGIOSHOME/etc/resource.cfg
cp -apv $NAGIOSHOME/etc/localhost.cfg-sample $NAGIOSHOME/etc/localhost.cfg
cp -apv $NAGIOSHOME/etc/cgi.cfg-sample $NAGIOSHOME/etc/cgi.cfg;echo

echo "[Setting administrative rights for 'nagiosadmin']"
echo "-------------------------------------------------";sleep 2s;echo
echo "" >> $NAGIOSHOME/etc/cgi.cfg
echo -e "#Setting administrative rights for 'nagiosadmin'\n" >> $NAGIOSHOME/etc/cgi.cfg

echo "authorized_for_system_information=nagiosadmin
authorized_for_configuration_information=nagiosadmin
authorized_for_system_commands=nagiosadmin
authorized_for_all_services=nagiosadmin
authorized_for_all_hosts=nagiosadmin
authorized_for_all_service_commands=nagiosadmin
authorized_for_all_host_commands=nagiosadmin" >> $NAGIOSHOME/etc/cgi.cfg

echo "[Creating additional configuration files :-]";
echo "--------------------------------------------";sleep 2s
touch $NAGIOSHOME/etc/hosts.cfg;
if [ $? -eq 0 ];then echo "Created $NAGIOSHOME/etc/hosts.cfg";else echo "Failed creating $NAGIOSHOME/etc/hosts.cfg";fi
touch $NAGIOSHOME/etc/hostgroups.cfg;
if [ $? -eq 0 ];then echo "Created $NAGIOSHOME/etc/hostgroups.cfg";else echo "Failed creating $NAGIOSHOME/etc/hostgroups.cfg";fi
touch $NAGIOSHOME/etc/contacts.cfg;
if [ $? -eq 0 ];then echo "Created $NAGIOSHOME/etc/contacts.cfg";else echo "Failed creating $NAGIOSHOME/etc/contacts.cfg";fi
touch $NAGIOSHOME/etc/contactgroups.cfg;
if [ $? -eq 0 ];then echo "Created $NAGIOSHOME/etc/contactgroups.cfg";else echo "Failed creating $NAGIOSHOME/etc/contactgroups.cfg";fi
touch $NAGIOSHOME/etc/services.cfg;
if [ $? -eq 0 ];then echo "Created $NAGIOSHOME/etc/services.cfg";else echo "Failed creating $NAGIOSHOME/etc/services.cfg";fi
touch $NAGIOSHOME/etc/timeperiods.cfg;
if [ $? -eq 0 ];then echo "Created $NAGIOSHOME/etc/timeperiods.cfg";else echo "Failed creating $NAGIOSHOME/etc/timeperiods.cfg";fi;
echo

echo "[Changing the ownership of newly created files :-]";
echo "--------------------------------------------------";sleep 2s
chown -Rv nagios.nagios $NAGIOSHOME/etc/*
echo

echo "" >> $NAGIOSHOME/etc/nagios.cfg
echo "[Setting config: file paths in $NAGIOSHOME/etc/nagios.cfg :-]";
echo "------------------------------------------------------------------";echo;sleep 2s
echo -e "#Setting configuration file paths.\n" >> $NAGIOSHOME/etc/nagios.cfg
echo "cfg_file=/usr/local/nagios/etc/hosts.cfg
cfg_file=/usr/local/nagios/etc/hostgroups.cfg
cfg_file=/usr/local/nagios/etc/services.cfg
cfg_file=/usr/local/nagios/etc/contacts.cfg
cfg_file=/usr/local/nagios/etc/contactgroups.cfg
cfg_file=/usr/local/nagios/etc/timeperiods.cfg" >> $NAGIOSHOME/etc/nagios.cfg

echo
echo "[Running the Nagios Syntax Check :-]";
echo "------------------------------------";sleep 1s
$NAGIOSHOME/bin/nagios -v $NAGIOSHOME/etc/nagios.cfg;echo
}

#################################
# [4]   Setting Up Apache       #
#################################

nagios_apache () {
echo "[Setting up Apache Web-Interface :-]"
echo "------------------------------------"

grep -q "### Nagios Script Alias ###" $APACHE_CONF;

if [ $? -eq 0 ];then
echo -e "ScriptAlias for nagios already exists in $APACHE_CONF\n"
/etc/init.d/httpd restart > /dev/null
else

echo "" >> $APACHE_CONF
echo -e "### Nagios Script Alias ###\n" >> $APACHE_CONF;

echo -e "ScriptAlias /nagios/cgi-bin /usr/local/nagios/sbin \n

Options ExecCGI
AllowOverride None
Order allow,deny
Allow from all
AuthName \"Nagios Access\"
AuthType Basic
AuthUserFile /usr/local/nagios/etc/htpasswd.users
Require valid-user
   \n" >> $APACHE_CONF

echo -e "Alias /nagios /usr/local/nagios/share  \n

Options None
AllowOverride None
Order allow,deny
Allow from all
AuthName \"Nagios Access\"
AuthType Basic
AuthUserFile /usr/local/nagios/etc/htpasswd.users
Require valid-user
   \n" >> $APACHE_CONF

echo "Added the needed Alias configurations in $APACHE_CONF"

echo -e "Restarting the Web-Server...please wait..\n"
/etc/init.d/httpd restart;
fi
}

nagios_htpasswd () {
echo "[Creating the login credentials for the nagios URL :-]"
echo "------------------------------------------------------";
echo "Username    : nagiosadmin"
htpasswd -c $NAGIOSHOME/etc/htpasswd.users nagiosadmin;echo
echo -e "Login to the Nagios Interface is now restricted to user 'nagiosadmin'.\n"
}

nagios_download && nagios_usercheck && nagios_previouscheck && nagios_ownership && nagios_configure && nagios_plugins && nagios_conf_files && nagios_apache && nagios_htpasswd

 

CHKROOTKIT install script (with functions)

This is an extension or a rebuild of the previous chkrootkit install script, just used functions so its somewhat simplified…. ( Or is it ..? 🙂 )


#!/bin/bash

DOWNLOAD_LOCATION='/root/Downloads'
CHKROOTKIT_WGET='ftp://ftp.pangeia.com.br/pub/seg/pac/chkrootkit.tar.gz'
RESULT_FILE='/root/Server-Test.txt'

clear;echo
chkrootkit-install () {

while true; do
echo -e "@@@@@@@@@@@@@@@@@@ CHK-ROOTKIT INSTALL/CHECK SCRIPT @@@@@@@@@@@@@@@@@@@@\n"
echo -e "Do you want to download and compile CHK-ROOTKIT [yes/no] ? : \c" | tee -a $RESULT_FILE;
read answer;
echo $answer >> $RESULT_FILE;

case $answer in
yes|YES)
echo
if [ ! -e $DOWNLOAD_LOCATION ]; then
echo -e "$DOWNLOAD_LOCATION does not exist, creating.......\n";sleep 1s
mkdir -p $DOWNLOAD_LOCATION;
fi
rm -rf $DOWNLOAD_LOCATION/chkrootkit* > /dev/null;
echo -e "Downloading CHK-ROOTKIT....\n" | tee -a $RESULT_FILE;sleep 1s
cd $DOWNLOAD_LOCATION && wget --progress=dot $CHKROOTKIT_WGET;
if [ $? -eq 0 ] ; then echo -e "Download finished..\n";
else echo -e "Sorry...Download Failed..!!!\n";exit;fi;echo
echo -e "Unpacking and compiling CHK-ROOTKIT..........\n";sleep 2s
cd $DOWNLOAD_LOCATION && tar -xvf chkrootkit*;
mv $DOWNLOAD_LOCATION/chkrootkit*gz $DOWNLOAD_LOCATION/1-chkrootkit.tar.gz;sleep 2s
cd $DOWNLOAD_LOCATION/chkrootki* && make sense > /dev/null;
if [ $? -eq 0 ] ; then echo -e "CHK-ROOTKIT compiled successfully..\n"| tee -a $RESULT_FILE;
break
else echo -e "CHK-ROOTKIT compilation failed, Quiting....\n" | tee -a $RESULT_FILE;
exit
fi
;;
no|NO)
echo
echo -e "Ok..As you wish....Aborting.\n"|tee -a $RESULT_FILE;
exit
;;
*)
echo
echo -e "Please enter either 'yes' OR 'no'..: \c"
;;
esac
done
}

chkrootkit-run () {
if [ -d $DOWNLOAD_LOCATION/chkrootki* ]; then
while true; do
echo -e "Do you want to run CHK-ROOTKIT now [yes/no] ? : \c" | tee -a $RESULT_FILE;
read reply
echo $reply >> $RESULT_FILE;

case $reply in
yes|YES)
echo
echo -e "Starting CHK-ROOTKIT....\n" | tee -a $RESULT_FILE;sleep 2s;echo
echo -e "----------------CHK-ROOTKIT SCAN RESULT-----------------\n"
$DOWNLOAD_LOCATION/chkrootk*/chkrootkit | tee -a $RESULT_FILE;sleep 1s
echo;echo -e "CHK-ROOTKIT check finished......\n";echo
exit
;;
no|NO)
echo
echo -e "DON'T FORGET TO RUN CHK-ROOTKIT PERIODICALLY.\n"
exit
;;
*)
echo
echo -e "Please enter either 'yes' OR 'no'..: \c"
;;
esac
done

else echo -e "Chkrootkit not found in $DOWNLOAD_LOCATION, exiting..\n"
fi

}

chkrootkit-install && chkrootkit-run;
echo -e "The result is saved in $RESULT_FILE for reference.\n"

 

Password Encryptor in C

Some time back, I had to implement a password encryption section in one of my bash programs. It seemed easy to use a C snippet rather than doing it in bash. This was something I got after searching a while.


#include stdlib.h
#include unistd.h
#include stdio.h
#include crack.h
#define DICTIONARY /usr/lib/cracklib_dict

int main(int argc, char *argv[]) {

char *password;
char *problem;

int status = 0;
printf(\nEnter an empty password or Ctrl-D to quit.\n);
while ((password = getpass(\nPassword: )) != NULL *password ) {
if ((problem = FascistCheck(password, DICTIONARY)) != NULL) {
printf(Bad password: %s.\n, problem);
status = 1;
}
else {
printf(Good password!\n);
}
}
exit(status);
}

Compile the code using the GNU C compiler.

# gcc filename.c -lcrack -o cracktest’