Thursday, 12 June 2014

Bash Exercises – 11

Bash Exercises – 11

Script 49: High CPU Usage Script |
At times, we need to monitor the high CPU usage in the system. We can use the below script to monitor the high CPU usage.
 #!/bin/bash   
  while [ true ] ;do   
  used=`free -m |awk 'NR==3 {print $4}'`   
  if [ $used -lt 1000 ] && [ $used -gt 800 ]; then   
  echo "Free memory is below 1000MB. Possible memory leak!!!" | /bin/mail -s "HIGH MEMORY ALERT!!!" user@mydomain.com   
  fi   
  sleep 5   
  done   

Script 50: Add new user |
This script allows the root user or admin to add new users to the system in an easier way by just typing the user name and password (The password is entered in an encrypted manner).
 #!/bin/bash  
 # 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  
   else  
     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!"  
   fi  
 else  
   echo "Only root may add a user to the system"  
   exit 2  
 fi  
Script 51: Database Backup |
This script is a pretty basic script useful in backing up the database.
 #!/bin/sh  
 now="$(date +'%d_%m_%Y_%H_%M_%S')"  
 filename="db_backup_$now".gz  
 backupfolder="/var/www/vhosts/example.com/httpdocs/backups"  
 fullpathbackupfile="$backupfolder/$filename"  
 logfile="$backupfolder/"backup_log_"$(date +'%Y_%m')".txt  
 echo "mysqldump started at $(date +'%d-%m-%Y %H:%M:%S')" >> "$logfile"  
 mysqldump --user=mydbuser--password=mypass --default-character-set=utf8 mydatabase | gzip > "$fullpathbackupfile"  
 echo "mysqldump finished at $(date +'%d-%m-%Y %H:%M:%S')" >> "$logfile"  
 chown myuser "$fullpathbackupfile"  
 chown myuser "$logfile"  
 echo "file permission changed" >> "$logfile"  
 find "$backupfolder" -name db_backup_* -mtime +8 -exec rm {} \;  
 echo "old files deleted" >> "$logfile"  
 echo "operation finished at $(date +'%d-%m-%Y %H:%M:%S')" >> "$logfile"  
 echo "*****************" >> "$logfile"  
 exit 0  

No comments :

Post a Comment