Tuesday, August 4, 2015

Script - Run script on remote server



1. Create an expect script to run the job on remote server.

$ cat .run_exp_sc
#! /usr/bin/expect --
#

###  encript your passwd  ###

set host_list [open [lindex $argv 0] r]

set pw [exec cat /home/kbhusal/bin/.pw | base64 -d]
set script [lindex $argv 1]

while {[gets $host_list host] != -1} {

        set timeout -1
        puts $host
        spawn -noecho $script $host
        expect "password for kbhusal: "
        send $pw\r
        interact

}


2. Create a script with the task you want
$ cat push_check_fs.sh

#! /bin/bash

ECHO_e='builtin echo -e'
SED='/bin/sed'
RM_f='/bin/rm -f'
CAT='/bin/cat'
SUDO='/usr/bin/sudo'

HOST=$1
WHOAMI=$(/usr/bin/whoami)
HOME="/home/${WHOAMI}"
BIN="${HOME}/bin/"
SCRIPT=$(${ECHO_e} ${0##*/} | ${SED} "s/push_//")
SCP_p='/usr/bin/scp -p'
SSH_t='/usr/bin/ssh -t'


${SCP_p} ${BIN}${SCRIPT} ${HOST}:${HOME} 2> /dev/null
${SSH_t} ${HOST} "${SUDO} ${HOME}/${SCRIPT}" 2> /dev/null


3. Add following lines below on your profile and relogin
$ cat .bash_profile
unset HISTFILE
set +o history
$ su - yourid

4. Now, convert your password to base64 or set it up to prompt for the password.

$ echo "your.pw.for.sudo" | base64 > /home/ur_home_dir/bin/.pw  (or the location where you want to store)

Note: Change the permission of these files to 700 and also assign ACL to make it more secure.

5. Now, Run your script
# .run.exp host_list ./push_check_fs.sh    

Note: host_list is a file with the list of servers by hostname or IP
$ cat host_list
server1
server2
server3 .....


$ cat chkeck_fs.sh
#!/bin/ksh
# Sam
# Check Filesystem thresold limit
# Root account expire info
#
PATH=$PATH:/bin/usr/bin; export PATH

fs_high=30
d_log=/tmp/df.out
rm $d_log
malert="sam@server.local"
ck_account=root
ex_acct=`sudo chage -l $ck_account | grep "Password expires"`
# chage -l root | grep "Password expires" >>$d_log
echo " ">>$d_log
echo " Info for `hostname` ">>$d_log
echo " -----------------------------">>$d_log
echo " ">>$d_log
echo "Account expiration info for $ck_account is:" >>$d_log
echo $ex_acct >>$d_log

df -hP | awk '{print $6 "\t\t\t" $5}' | grep -v Use | while read dfout;
do
        p_use=$(echo $dfout | awk '{print $2}' | cut -d'%' -f1)
        fs_ck=$(echo $dfout | awk '{print $1}')

if [ $p_use -gt $fs_high ];     then
        echo " Please check \"$fs_ck ($p_use%)\" on $(hostname)" >> $d_log
        # echo " Please check \"$fs_ck ($p_use%)\" on $(hostname)" | \
        # mailx -s " Please check the filesystem " $malert
fi
done
cat /tmp/df.out
echo "----------- End --------------"




No comments:

Post a Comment