Get Days in a month from a bash script

Useful listing of days in a month to populate directories or run scripts for backing up getting the correct dates of days in a month and year.

 

 


YEAR=2020
MONTH=2

for DAY in $(DAYS=`cal $MONTH $YEAR | awk 'NF {DAYS = $NF}; END {print DAYS}'` && seq -f '%02G' $DAYS) ;do
DATE="$YEAR-$MONTH-$DAY"
echo $DATE
done

nJoy 😉

incrond cannot exec process: No such file or directory

Inside your incrontabs, you must leave *only* 1 space between the <path> <mask> <cmd>. If you leave 2 or more spaces, then the 2nd (and more) spaces will be considered part of the <mask> or <cmd> and it will fail… I was leaving 2 spaces between <mask> and <cmd>, and incron did not work and in /var/log/syslog there were these messages

incrond[27693]: cannot exec process: No such file or directory

This was because of having 2 spaces… when I corrected to only 1 space, it began working correctly. Keep it in mind, so you dont suffer as much as I did to find it out 🙂

After editing with “incrontab -e”, check that “incrontab -l” shows the rules. If it does not show some rule, then that is because that rule has some error and was not recognized.

To debug what is happening behind the curtains, its usefull to have a “tail -f /var/log/syslog” on another terminal…

Quoted from https://zipizap.wordpress.com/2013/11/15/incron/

Very useful thanks !

😉 nJoy

Cool chkconfig replacement for Ubuntu

Hi,

 

Ubuntu does not carry chkconfig any more ..

besides the standard

update-rc.d apache2 defaults

or

update-rc.d apache2 remove

There is a cool tool called : sysv-rc-conf.

This tool can be installed using :

sudo apt-get install sysv-rc-conf

On its own the command opens a cool ncurses interface like this :

 

 

 

 

 

 

 

 

 

It can Also be used in scripts as :

sysv-rc-conf atd <on or off> and --levels;

man sysv-rc-conf

Will give you some love..

nJoy 😉

 

 

Snapshot backup using cp -al and rsync

This script requires genuine cp -al capable gnu and rsync commands together with a hardlink capable FS + OS.

 

 

#!/bin/bash

[ $# -ne 2 ] && echo "Incorrect usage : $0 <source path> <target path>" && exit 128 ;

SOURCEFOLDER=$1
TARGETFOLDER=$2

SF_LEN=${#SOURCEFOLDER}-1
TF_LEN=${#TARGETFOLDER}-1

#echo "Last character in source folder is ${SOURCEFOLDER:SF_LEN}"
if [ "${SOURCEFOLDER:SF_LEN}" != "/" ] ; then
   echo "Adding trailing slash"
  SOURCEFOLDER=$SOURCEFOLDER"/"
fi



#echo "Last character in target folder is ${TARGETFOLDER:TF_LEN}"
if [ "${TARGETFOLDER:TF_LEN}" != "/" ] ; then
   echo "Adding trailing slash"
  TARGETFOLDER=$TARGETFOLDER"/"
fi



echo $SOURCEFOLDER
echo $TARGETFOLDER

LOCKFILE=/tmp/`echo $0 $SOURCEFOLDER $TARGETFOLDER | sed "s/[^[:alnum:]]/_/g"`.lck
echo "Lockfile : $LOCKFILE"



[ ! -d $SOURCEFOLDER ] && echo "Source does not exist !! $SOURCEFOLDER exitting with error" && exit 1;

TIMESTAMP=$(date --utc +%Y%m%d%H%M )
#echo $TIMESTAMP



if [ ! -d $TARGETFOLDER ]; then 

mkdir $TARGETFOLDER

rsync -av --delete  $SOURCEFOLDER $TARGETFOLDER/$TIMESTAMP/

else 

[ -d $TARGETFOLDER/$TIMESTAMP/ ] && echo "Folder already there !! Leaving.. " && exit 0;  

 LASTBACKUP=$(ls $TARGETFOLDER | sort -rn | head -1)
 echo "Link copying $TARGETFOLDER/$LASTBACKUP to $TARGETFOLDER/$TIMESTAMP/"
 cp -al $TARGETFOLDER/$LASTBACKUP $TARGETFOLDER/$TIMESTAMP/
 rsync -av $SOURCEFOLDER $TARGETFOLDER/$TIMESTAMP/

fi

echo " OK !! Done"

 

 

 

Script to verify that a path is synchronized across multiple machines via ssh

This is a script I wrote for work to look through a number of remote servers via ssh (shared keys or include a .pem (id_rsa) file to compare a paths and all it’s subfolders.

The result is a report of which files are out of synch and if duplicates found they are listed separately.

#!/bin/bash
## Parameters  sync_check [-i id.pem] [-u <user for ssh>] -p <path_to_diff>  <target-system-IP1> <target-system-IP2> ...

# David Saliba [dx@sudoall.com]

RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color


PEMFILE=""
SSH_USER="root"

function usage {
	echo 
	echo -e "\t$0 usage as follows :"
	echo -e "\t$0 [-i <pem_file>] [-u <ssh_user_name>] -p <path_to_diff> <ref-system-IPADDR1> <target-system-IP1> <target-system-IP2>..."
	echo 
}


[ $# -le 2 ] && echo && echo -e "${RED}Incorrect number of parameters ${NC}" && usage && exit 128


while getopts "i:u:p:" opt; do
echo $opt $OPTARG
  case $opt in
  	i ) PEMFILE=$OPTARG; shift $((OPTIND-1)); OPTIND=1 ; 
          if [[ -f "$PEMFILE" ]]; then 
              PEMFILE="-i ""$PEMFILE" 
          else
          	  echo "Pemfile : $PEMFILE not found. Quitting .. " 
          	  exit 1  
          fi
          ;;
	u ) SSH_USER=$OPTARG ; shift $((OPTIND-1)); OPTIND=1 ;;
	p ) PATH_TO_CHECK=$OPTARG ; shift $((OPTIND-1)); OPTIND=1 ;;
    * ) usage
       exit 128
  esac
done



extfile="_target.md5.sync_check"

		echo; echo

rm -f /tmp/*.sync_check
for i in $* ; do
	ipcalc -cs $i
	if [ $? == 0 ] ; then
		echo -n "Retrieving Signature List from ..  :[$i] : " 
		ssh $PEMFILE $SSH_USER@$i "hostname"

		COMMAND="ssh $PEMFILE $SSH_USER@$i \"find  $PATH_TO_CHECK -type f -exec md5sum {} \\; | sed -e 's/^/$i\t/'| sort -k 2 \""
		#echo "Running : $COMMAND  /tmp/$i""_target.md5.sync_check"
		bash -c "$COMMAND" > /tmp/$i$extfile
		
	else
		echo "Parameter $i not a valid IP skipping .."
	fi
done

echo ;echo; echo "Comparing data ... "; echo

 OLDIFS=$IFS; 
 IFS=$'\n'; 

 for i in `cat /tmp/*.sync_check  | sort -k3 | uniq -f 1 -c | sort | egrep -v "^[\ \t]*$#" | sort -k4 ` ;do 
 	
 	NUMBER_OF_HITS=`echo "$i" | awk '{print ($1)}'`

 	echo $i

 	if [ $NUMBER_OF_HITS -gt 1 ] ; then
 		
 		MD5Onward=`echo "$i" | awk '{print substr($0, index($0,$3))}'`
		echo -e -n "${YELLOW}"	
			grep -h "$MD5Onward" /tmp/*.sync_check  | awk '{print "\t\t",NR, $0}'
		echo -e -n "${NC}"	


 	fi


 done ;

 IFS=$OLDIFS


echo
echo




link to file here: http://jist.sudoall.com/sync_check/sync_check.sh

nJoy 😉

Progress bar in bash

a=0;
for i in `cat $FOLDERLIST`
do
((a++))
percentage=`awk -v a=$a -v b=$NUMBEROFFOLDERS 'BEGIN {printf "%3.0f", a / b * 100; exit } '`

arrow=`printf '=%.0s' $(seq 1 $percentage)`
headed=`printf '%s%s' $arrow '>'`
paddedarrow=`printf '%-102s' $headed`
echo -ne "$paddedarrow  $a/$NUMBEROFFOLDERS [$percentage] \r "
done
echo

njoy  😉

pre-pend log timestamp

Adds a timestamp before alog from a script

awk -v sec=$(date -u +%s) '{print strftime("%Y-%m-%d %H:%M:%S",sec), $0; fflush();}'

in cron :

awk -v sec=$(date -u +\%s) '{print strftime("\%Y-\%m-\%d \%H:\%M:\%S",sec), $0; fflush();}'

So :

# echo hello world | awk -v sec=$(date -u +%s) '{print strftime("%Y-%m-%d %H:%M:%S",sec), $0; fflush();}'

 

2014-10-30 08:40:26 test

nJoy 🙂

VBS script to gather all IIS 6 Sites , state and folders for storage

This is a script from this site which I found particularly handy.

OPTION EXPLICIT

DIM CRLF, TAB
DIM strServer
DIM objWebService

TAB  = CHR( 9 )
CRLF = CHR( 13 ) & CHR( 10 )

IF WScript.Arguments.Length = 1 THEN
    strServer = WScript.Arguments( 0 )
ELSE
    strServer = "localhost"
END IF

WScript.Echo "Enumerating websites on " & strServer & CRLF
SET objWebService = GetObject( "IIS://" & strServer & "/W3SVC" )
EnumWebsites objWebService

SUB EnumWebsites( objWebService )
    DIM objWebServer, objWebServerRoot, strBindings
    DIM myFSO
    DIM WriteStuff
    DIM tmp 

    Set myFSO = CreateObject("Scripting.FileSystemObject")
    Set WriteStuff = myFSO.OpenTextFile("siteList.txt", 8, True)
    tmp = "Site ID|Comment|State|Path|LogDir|HostHeaders|SecHostHeaders"
    WriteStuff.WriteLine(tmp)

    FOR EACH objWebServer IN objWebService
        IF objWebserver.Class = "IIsWebServer" THEN
        SET objWebServerRoot = GetObject(objWebServer.adspath & "/root")
            tmp = objWebserver.Name & "|" & _
                objWebServer.ServerComment & "|" & _ 
                State2Desc( objWebserver.ServerState ) & "|" & _ 
                objWebServerRoot.path & "|" & _ 
                objWebServer.LogFileDirectory & "|" & _   
                EnumBindings(objWebServer.ServerBindings) & "|" & _
        EnumBindings(objWebServer.SecureBindings) & "|" & _
        ""
            WriteStuff.WriteLine(tmp)
        END IF
    NEXT

END SUB

FUNCTION EnumBindings( objBindingList )
    DIM i, strIP, strPort, strHost
    DIM reBinding, reMatch, reMatches
    SET reBinding = NEW RegExp
    reBinding.Pattern = "([^:]*):([^:]*):(.*)"
    EnumBindings = ""
    FOR i = LBOUND( objBindingList ) TO UBOUND( objBindingList )
        ' objBindingList( i ) is a string looking like IP:Port:Host
        SET reMatches = reBinding.Execute( objBindingList( i ) )
        FOR EACH reMatch IN reMatches
            strIP = reMatch.SubMatches( 0 )
            strPort = reMatch.SubMatches( 1 )
            strHost = reMatch.SubMatches( 2 )

            ' Do some pretty processing
            IF strIP = "" THEN strIP = "All Unassigned"
            IF strHost = "" THEN strHost = "*"
            IF LEN( strIP ) < 8 THEN strIP = strIP & TAB

        EnumBindings = EnumBindings & strHost & "," & ""
        NEXT    
    NEXT
    if len(EnumBindings) > 0 Then EnumBindings = Left(EnumBindings,Len(EnumBindings)-1)
END FUNCTION

FUNCTION State2Desc( nState )
    SELECT CASE nState
    CASE 1
        State2Desc = "Starting (MD_SERVER_STATE_STARTING)"
    CASE 2
        State2Desc = "Started (MD_SERVER_STATE_STARTED)"
    CASE 3
        State2Desc = "Stopping (MD_SERVER_STATE_STOPPING)"
    CASE 4
        State2Desc = "Stopped (MD_SERVER_STATE_STOPPED)"
    CASE 5
        State2Desc = "Pausing (MD_SERVER_STATE_PAUSING)"
    CASE 6
        State2Desc = "Paused (MD_SERVER_STATE_PAUSED)"
    CASE 7
        State2Desc = "Continuing (MD_SERVER_STATE_CONTINUING)"
    CASE ELSE
        State2Desc = "Unknown state"
    END SELECT

END FUNCTION

Works like a charm..

 

nJoy 😉

Screen script for multi-user session or reminding you to create a screen on logon

A common problem when many people share large systems as the same user ( I know .. I know but anyways move on )  is that when you logon you might want to take over where someone else left off. Also sometimes you want to share a session with someone for supervision or just team experience.

Screen tool in linux is fantastic for this. I wrote this script to allow people to be reminded to have a screen session and if already there allow you to log on to the screen by either taking over the session or sharing it with the other user.

installation of screen is as easy as :

 

sudo yum install screen -y

or for you debbie penguins out there

 

sudo apt-get install screen -y

 

The script goes like this :

## Screen profile for user session sharing
## by David Saliba (copyleft) 2013 

#!/bin/bash

function greet {
 clear
 cat /etc/motd
 echo "Hostname:" `hostname `
 echo
 ifconfig | grep inet | egrep -v "inet6|localhost|127\.0\.0\.1"
 echo
 #  df -h /
 echo "Welcome ! #  No screen session  #"   
}

function newscreen {

 echo "Would you like to create a new session  ? (Y/n)"

  read -t 10 b
  if [[ $b == "N" || $b == "n" ]]; then
 { # Dummy if no just continue
  echo 
 }
 else
 {
  
  echo " Remember to use <CTRL> + A and then d to leave the screen session active or just disconnect "
  echo -n "Creating "
         sleep 1; echo -n "." ;sleep 1; echo -n "."; sleep 1; echo -n "."
  exec screen -S Workarea
 }
 fi
}

if [ -z "$STY" ]; then
 firstscreen=$(screen -list | grep "(" | cut -f 2 | head -n 1)
# echo $firstscreen

 if [ ! -z "$firstscreen" ]; then
 {
         echo "Found screen ($firstscreen).Do you want to jump on it (Y), or share the session (X)? (Default Y in 10s)"
         read -t 10 a
     if [[ $a == "N" || $a == "n" ]]; then
        {
         greet
        }
     elif [[ $a == "X" || $a == "x" ]]; then
        {
         echo -n "Joining "
         sleep 1; echo -n "." ;sleep 1; echo -n ".";
         exec screen -x $firstscreen
        }
     else
        {
         echo -n "Connecting and taking over"
         sleep 1; echo -n "." ;sleep 1; echo -n ".";
         exec screen -r -d $firstscreen
        }
     fi
 }
 else
 {
   greet   str3amuK
   newscreen
 }
 fi
fi

 

Save this script under /etc/profile.d/screen.sh or some other name you will recognize.