5 Important scripts useful for a Linux system administrator

While all the scripts provided below may be accurate, there may be much more advanced features available. However, these scripts are just to give an overview of how things are meant to be done for a systems administrator. I did not make any of the below scripts and all scripts’ references are given inline along with their description.

Disk usage

This script will be useful to analyze the disk usage and if the reported disk space is more than 90 % an email will be sent to the administrator. The script is taken from here.

#!/bin/sh
# set -x
# Shell script to monitor or watch the disk space
# It will send an email to $ADMIN, if the (free available) percentage of space is >= 90%.
# -------------------------------------------------------------------------
# Set admin email so that you can get email.
ADMIN="root"
# set alert level 90% is default
ALERT=90
# Exclude list of unwanted monitoring, if several partions then use "|" to separate the partitions.
# An example: EXCLUDE_LIST="/dev/hdd1|/dev/hdc5"
EXCLUDE_LIST="/auto/ripper"
#
#::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
#
function main_prog() {
while read output;
do
#echo $output
  usep=$(echo $output | awk '{ print $1}' | cut -d'%' -f1)
  partition=$(echo $output | awk '{print $2}')
  if [ $usep -ge $ALERT ] ; then
     echo "Running out of space \"$partition ($usep%)\" on server $(hostname), $(date)" | \
     mail -s "Alert: Almost out of disk space $usep%" $ADMIN
  fi
done
}
if [ "$EXCLUDE_LIST" != "" ] ; then
  df -H | grep -vE "^Filesystem|tmpfs|cdrom|${EXCLUDE_LIST}" | awk '{print $5 " " $6}' | main_prog
else
  df -H | grep -vE "^Filesystem|tmpfs|cdrom" | awk '{print $5 " " $6}' | main_prog
fi

Incremental Backup Scripts

This script will do the incremental backup into an external mounted hard-drive. It is to take a backup of the /home directory. However, it can be modified to suit the requirements. The script is taken from here.

#!/bin/bash
# ----------------------------------------------------------------------
# mikes handy rotating-filesystem-snapshot utility
# ----------------------------------------------------------------------
# this needs to be a lot more general, but the basic idea is it makes
# rotating backup-snapshots of /home whenever called
# ----------------------------------------------------------------------

unset PATH  # suggestion from H. Milz: avoid accidental use of $PATH

# ------------- system commands used by this script --------------------
ID=/usr/bin/id;
ECHO=/bin/echo;

MOUNT=/bin/mount;
RM=/bin/rm;
MV=/bin/mv;
CP=/bin/cp;
TOUCH=/bin/touch;

RSYNC=/usr/bin/rsync;


# ------------- file locations -----------------------------------------

MOUNT_DEVICE=/dev/hdb1;
SNAPSHOT_RW=/root/snapshot;
EXCLUDES=/usr/local/etc/backup_exclude;


# ------------- the script itself --------------------------------------

# make sure we're running as root
if (( `$ID -u` != 0 )); then { $ECHO "Sorry, must be root.  Exiting..."; exit; } fi

# attempt to remount the RW mount point as RW; else abort
$MOUNT -o remount,rw $MOUNT_DEVICE $SNAPSHOT_RW ;
if (( $? )); then
{
    $ECHO "snapshot: could not remount $SNAPSHOT_RW readwrite";
    exit;
}
fi;


# rotating snapshots of /home (fixme: this should be more general)

# step 1: delete the oldest snapshot, if it exists:
if [ -d $SNAPSHOT_RW/home/hourly.3 ] ; then         \
$RM -rf $SNAPSHOT_RW/home/hourly.3 ;                \
fi ;

# step 2: shift the middle snapshots(s) back by one, if they exist
if [ -d $SNAPSHOT_RW/home/hourly.2 ] ; then         \
$MV $SNAPSHOT_RW/home/hourly.2 $SNAPSHOT_RW/home/hourly.3 ; \
fi;
if [ -d $SNAPSHOT_RW/home/hourly.1 ] ; then         \
$MV $SNAPSHOT_RW/home/hourly.1 $SNAPSHOT_RW/home/hourly.2 ; \
fi;

# step 3: make a hard-link-only (except for dirs) copy of the latest snapshot,
# if that exists
if [ -d $SNAPSHOT_RW/home/hourly.0 ] ; then         \
$CP -al $SNAPSHOT_RW/home/hourly.0 $SNAPSHOT_RW/home/hourly.1 ; \
fi;

# step 4: rsync from the system into the latest snapshot (notice that
# rsync behaves like cp --remove-destination by default, so the destination
# is unlinked first.  If it were not so, this would copy over the other
# snapshot(s) too!
$RSYNC                              \
    -va --delete --delete-excluded              \
    --exclude-from="$EXCLUDES"              \
    /home/ $SNAPSHOT_RW/home/hourly.0 ;

# step 5: update the mtime of hourly.0 to reflect the snapshot time
$TOUCH $SNAPSHOT_RW/home/hourly.0 ;

# and thats it for home.

# now remount the RW snapshot mountpoint as readonly

$MOUNT -o remount,ro $MOUNT_DEVICE $SNAPSHOT_RW ;
if (( $? )); then
{
    $ECHO "snapshot: could not remount $SNAPSHOT_RW readonly";
    exit;
} fi;

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. The script is taken from here.

#!/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

Adding new users to a Linux system

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). The below script is taken from here.

#!/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

Database Backup

This script is a pretty basic script useful in backing up the database. The script is taken from here.

#!/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

Source : http://unix.stackexchange.com/questions/125726/important-scripts-useful-for-a-linux-system-administrator

Script : Color_bash.sh

Travaillant actuellement sur une fonction d’affichage pour les scripts bash, je vous partage un petit qui vous affichera dans le terminal les couleurs et leur code associé en bash.

#!/bin/bash
#
#   This file echoes a bunch of color codes to the
#   terminal to demonstrate what's available.  Each
#   line is the color code of one forground color,
#   out of 17 (default + 16 escapes), followed by a
#   test use of that color on all nine background
#   colors (default + 8 escapes).
#
#   Author: Giles Orr
#   URL: http://gilesorr.com/bashprompt/howto/c350.html
#   License: GNU Free Documentation License, Version 1.1 or any later version published by the Free Software Foundation;
#            http://gilesorr.com/bashprompt/howto/a1004.html


T='gYw'   # The test text

echo -e "\n                 40m     41m     42m     43m\
     44m     45m     46m     47m";

for FGs in '    m' '   1m' '  30m' '1;30m' '  31m' '1;31m' '  32m' \
           '1;32m' '  33m' '1;33m' '  34m' '1;34m' '  35m' '1;35m' \
           '  36m' '1;36m' '  37m' '1;37m';
  do FG=${FGs// /}
  echo -en " $FGs \033[$FG  $T  "
  for BG in 40m 41m 42m 43m 44m 45m 46m 47m;
    do echo -en "$EINS \033[$FG\033[$BG  $T  \033[0m";
  done
  echo;
done
echo

echo -e "\e[0mNO_COLOR"
echo -e "\e[1;37mCOLOR_WHITE\t\e[0;30mCOLOR_BLACK"
echo -e "\e[0;34mCOLOR_BLUE\t\e[1;34mCOLOR_LIGHT_BLUE"
echo -e "\e[0;32mCOLOR_GREEN\t\e[1;32mCOLOR_LIGHT_GREEN"
echo -e "\e[0;36mCOLOR_CYAN\t\e[1;36mCOLOR_LIGHT_CYAN"
echo -e "\e[0;31mCOLOR_RED\t\e[1;31mCOLOR_LIGHT_RED"
echo -e "\e[0;35mCOLOR_PURPLE\t\e[1;35mCOLOR_LIGHT_PURPLE"
echo -e "\e[0;33mCOLOR_YELLOW\t\e[1;33mCOLOR_LIGHT_YELLOW"
echo -e "\e[1;30mCOLOR_GRAY\t\e[0;37mCOLOR_LIGHT_GRAY"

skynet.tomzone.fr - PuTTY_2

Source : https://github.com/fikovnik/bin-scripts

Script – Changer le hostname d’un serveur CentOS – RedHat

Dans les outils utiles, mention spéciale pour distribuer aux petits admin qui doivent renommer leur serveur RedHat / CentOS.

Ce petit script vous changera le hostname de votre serveur sous CentOS et RedHat sans redémarrer la machine. Simple. Efficace.

#!/bin/bash

#################################
#    FILE: change_hostname.sh   #
#    VERSION: 0.1               #
#    DATE: 08-04-2015           #
#                               #
#    AUTHOR: Thomas Bourcey     #
#################################

#############################################
#  USAGE :                                  #
#  $ sh change_hostname.sh new_hostname     #
#  or                                       #
#  $ sh change_hostname.sh                  #
#  Please enter new hostname: new_hostname  #
#############################################


if [ $EUID -ne 0 ]; then
        echo "The script must be run as root: # su - -c $0 or # sudo ./$0"
        exit 1
fi

$ command -v lsb_release >/dev/null 2>&1 || { echo >&2 "Package redhat-lsb-core is required. Download it \"yum install -y redhat-lsb-core\".  Aborting."; exit 1; }

if [ `lsb_release -a | grep -i Distributor | awk -F":" '{print $2}' | tr -d '[ \t ]'` != "RedHatEnterpriseServer" ]; then
        echo "Only for RedHat Distribution. Exiting !"
        exit 2
fi

OLD_HOSTNAME="$( hostname )"
NEW_HOSTNAME="$1"

if [ -z "$NEW_HOSTNAME" ]; then
 echo -n "Please enter new hostname: "
 read NEW_HOSTNAME < /dev/tty
fi

if [ -z "$NEW_HOSTNAME" ]; then
 echo "Error: no hostname entered. Exiting."
 exit 1
fi

echo "Changing hostname from $OLD_HOSTNAME to $NEW_HOSTNAME..."

hostname "$NEW_HOSTNAME"

sed -i "s/HOSTNAME=.*/HOSTNAME=$NEW_HOSTNAME/g" /etc/sysconfig/network

if [ -n "$( grep "$OLD_HOSTNAME" /etc/hosts )" ]; then
 sed -i "s/$OLD_HOSTNAME/$NEW_HOSTNAME/g" /etc/hosts
else
 echo -e "$( hostname -I | awk '{ print $1 }' )\t$NEW_HOSTNAME" >> /etc/hosts
fi

echo "Done."

 

 

Shc – Shell script compiler

Shc est un programme qui permet de compiler des scripts shell afin d’obtenir un binaire. Cette méthode offre plusieurs avantages aux développeurs. Tout d’abord, elle permet de distribuer un logiciel sans forcément fournir son code source. Ensuite, shc propose une option qui propose de positionner une date d’expiration. Cette fonctionnalité sera intéressante dans le cadre d’une distribution de logiciels avec une licence qui expire dans le temps ou d’un version beta que l’on veut bloquer.

Vous me direz quel est l’intérêt de ne pas fournir le code source ? Je pense dans le milieu des entreprises, lorsque l’on fournit à des utilisateurs travaillant sur des stations Linux des scripts ou des wrappers, il peut être intelligent de fermer le code pour éviter une utilisation détournée des scripts.

shc est quand même loin de fournir des binaires infaillibles. Des crackers peuvent facilement désassembler le fichier afin d’obtenir le code source. Néanmoins, cela découragera la plupart des utilisateurs.

Continuer la lecture de Shc – Shell script compiler