Sunday, February 6, 2022

Make sure a process is running?

I have a openvpn tunnel up normally for certain things and want to kill some processes
if the tunnel goes down…

Check every minute

* * * * * /root/bin/tun.up.sh >> /var/log/tunnel.up.log

Which checks for the tunnel tun0 and kill some processes if it’s not.

IFCONFIG=/sbin/ifconfig
GREP=/usr/bin/grep
ECHO=/usr/bin/echo
AWK=/usr/bin/awk
PS=/usr/bin/ps
PKILL=/usr/bin/pkill
DATE=`/usr/bin/date +"%m.%d.%y.%H.%M"`
PGREP=/usr/bin/pgrep

TEST=`$IFCONFIG | $GREP tun | $AWK '{print $1}'`
TOKILL=`$PS | $GREP ktorrent`

if [ $TEST == "tun0:" ]; then
 $ECHO $TEST " UP " $DATE
 exit
fi

PROC=`$PGREP ktorrent`
#$ECHO "Killing " $PROC
$ECHO $TEST " DOWN " $DATE
$PKILL -f ktorrent

Going to write a bit more code in the near future to bring the tunnel back up when it goes down
but that’s something for a different day.

Killing a process every day at certain time?

Gotta Schedule it with crontab -e (I use joe a wordstar equivalent)

alias cron='crontab -e'

=====================================================

root@ms2:/home/timc/bin# select-editor

Select an editor.  To change later, run 'select-editor'.
  1. /usr/bin/joe
  2. /usr/bin/jstar
  3. /usr/bin/jpico
  4. /usr/bin/jmacs
  5. /bin/nano        <---- easiest
  6. /usr/bin/vim.basic
  7. /usr/bin/rjoe
  8. /usr/bin/vim.tiny
  9. /bin/ed

=====================================================

4 0 * * * /home/timc/bin/kill.exp.sh &> /var/log/kill.log

===========================================================

#!/bin/bash
#ps -elf | grep chia | grep exp > t

TOUCH=/usr/bin/touch
ECHO=/usr/bin/echo
CHMOD=/usr/bin/chmod
RM=/usr/bin/rm
PS=/usr/bin/ps
CAT=/usr/bin/cat
GREP=/usr/bin/grep
AWK=/usr/bin/awk

DIR="/home/timc/bin"
TMPFILE="temp.kill.file"
KILLFILE="kill.up.exp.sh"

$RM $DIR/$TMPFILE
$RM $DIR/$KILLFILE
$TOUCH $DIR/$TMPFILE
$TOUCH $DIR/$KILLFILE

$PS -elf | $GREP chia | $GREP exp | $AWK '{print $4}' >> $TMPFILE

$ECHO "Start kill file to exec  (kill.up.exp.sh)"
$CAT $DIR/$TMPFILE | while read line
do
  $ECHO kill -9 $line >> $DIR/$KILLFILE
done
$CHMOD 755 $DIR/$KILLFILE
$DIR/$KILLFILE