Bash script to check if process is running and read user input to start if necessary - linux

Having a problem with using nohup in a script. The script works properly if nohup is not used
to start the process. The following error is received when run:
./iper.sh: line 16: syntax error near unexpected token `;'
./iper.sh: line 16: ` [Yy]*) nohup iperf -s > /dev/null 2>&1&; break;;'
Here is the full script:
#!/bin/bash
echo "Checking to see if Iperf is running:"
sleep 2
ps cax | grep iperf > /dev/null
if [ $? -eq 0 ]; then
echo "Iperf is running."
else
echo "Iperf is not running."
fi
sleep 2
while true; do
read -p "Press Y to start Iperf or N to exit: " yn
case $yn in
[Yy]*) nohup iperf -s > /dev/null 2>&1&; break;;
[Nn]*) exit;;
esac
done
What is happening?

If you're going to terminate your command with & to put it to background, do not terminate it with another semicolon ; as well:
[Yy]*) nohup iperf -s > /dev/null 2>&1& break;;
Previously
2>&1&;

I guess you have an extra & in 2>&1&
Change it to 2>&1

Check with below script
#!/bin/bash
echo "Checking to see if Iperf is running:"
sleep 1
if `pgrep iperf >/dev/null 2>&1`
then
echo "iperf Running"
else
echo "iperf not Running"
fi
sleep 1
while true; do
echo "Do you wanna start Iperf (y/n)"
read -n 1 ch; p=`echo ${ch} | tr A-Z a-z`
case $p in
y)nohup iperf -s > /dev/null 2>&1 break;;
n)exit;;
*)continue;
esac
done
when this been executed it waits for user to press*ctrl + c* to come out
if you are using 2>&1&(for continuing without user interference)allowing user to do other work
replace below line in y) condition
nohup iperf -s > /dev/null 2>&1& break;;

Related

Script guide to prevent duplicate execution of jar in Linux

Jar should run in the background and not run redundantly.
Even if duplicate execution occurs, all must be terminated
#!/bin/bash
ENV=dev
SER_NAME=batch
JAR_FULL=/was/batch/test.jar
case $1 in
restart)
if apid=$(pgrep -f $SER_NAME)
then
for pid in $apid; do
echo "Stop $SER_NAME pid : $pid"
kill -9 $pid
done
else
echo "$SER_NAME is not running ... "
fi
nohup java -jar $JAR_FULL --spring.profiles.active=$ENV > /dev/null 2>&1 &
echo "$SER_NAME" start"
;;
stop)
if apid=$(pgrep -f $SER_NAME)
then
for pid in $apid; do
echo "Stop $SER_NAME - pid : $pid"
kill -9 $pid
done
else
echo "$SER_NAME is not running ..."
fi
;;
start)
if apid=$(pgrep -f $SER_NAME)
then
echo "$SER_NAME is already running ..."
for pid in $apid; do
echo "Running $SER_NAME -pid : $pid"
done
else
nohup java -jar $JAR_FULL --spring.profiles.active=$ENV > /dev/null 2>&1 &
echo "$SER_NAME start!"
fi
;;
esac
example) run.sh
console) chmod 755 run.sh
console) ./run.sh start
start or stop or restart

How to run the bash script in parallel rather than sequentially?

#!/bin/bash
some_array=($1)
echo "-- Setting-Up VM --"
for i in ${some_array[#]}; do
echo "VM #: $i"
case "$i" in
"1")
echo "Setting-Up VM $i"
sshpass -p "root12" ssh -tt -o StrictHostKeyChecking=no root#10.xx.x.xx <<EOF
pwd
nohup yes | /etc/rc.d/init.d/lifconfig
su tarts
nohup yes | vncserver
sleep 10
exit
exit
EOF
;;
"2")
echo "Setting-Up VM $i"
sshpass -p "root12" ssh -tt -o StrictHostKeyChecking=no root#10.xx.x.xx <<EOF
pwd
nohup yes | /etc/rc.d/init.d/lifconfig
su tarts
nohup yes | vncserver
sleep 10
exit
exit
EOF
;;
"3")
echo "Setting-Up VM $i"
sshpass -p "root12" ssh -tt -o StrictHostKeyChecking=no root#10.xx.x.xx <<EOF
pwd
nohup yes | /etc/rc.d/init.d/lifconfig
su tarts
nohup yes | vncserver
sleep 10
exit
exit
EOF
;;
*)
echo "unknown VM!"
;;
esac
done
Can someone please guide me I have the above script which is executed when we run the script for instance ./vmSetup.sh "1 2 3" but this is executed sequentially. I had created this script but now I want to run the cases in the script i.e. 1, 2 and 3 in parallel. Can someone also tell me how to run for instance 8 cases in parallel?
Put each case ... esac statement in the background by ending it with &. Then use wait after the loop to wait for all the background processes to finish.
#!/bin/bash
some_array=($1)
echo "-- Setting-Up VM --"
for i in ${some_array[#]}; do
echo "VM #: $i"
case "$i" in
"1")
echo "Setting-Up VM $i"
sshpass -p "root12" ssh -tt -o StrictHostKeyChecking=no root#10.xx.x.xx <<EOF
pwd
nohup yes | /etc/rc.d/init.d/lifconfig
su tarts
nohup yes | vncserver
sleep 10
exit
exit
EOF
;;
"2")
echo "Setting-Up VM $i"
sshpass -p "root12" ssh -tt -o StrictHostKeyChecking=no root#10.xx.x.xx <<EOF
pwd
nohup yes | /etc/rc.d/init.d/lifconfig
su tarts
nohup yes | vncserver
sleep 10
exit
exit
EOF
;;
"3")
echo "Setting-Up VM $i"
sshpass -p "root12" ssh -tt -o StrictHostKeyChecking=no root#10.xx.x.xx <<EOF
pwd
nohup yes | /etc/rc.d/init.d/lifconfig
su tarts
nohup yes | vncserver
sleep 10
exit
exit
EOF
;;
*)
echo "unknown VM!"
;;
esac &
done
wait
Why do you have a case statement at all when all these are identical?
#!/bin/bash
echo "-- Setting-Up VM(s) --"
for i in "$#"; do
case "$i" in
1) IP=1.2.3.4;;
2) IP=2.2.3.4;;
3) IP=3.2.3.4;;
*) echo "Invalid option '$i'" >&2; exit 1;;
esac
echo "Setting-Up VM $i"
sshpass -p root12 ssh -tt -o StrictHostKeyChecking=no root#$IP <<EOF &
pwd
nohup yes | /etc/rc.d/init.d/lifconfig
su tarts
nohup yes | vncserver
sleep 10
exit
exit
EOF
done
To run a job in background, just use &
sshpass -p "root12" ssh -tt -o StrictHostKeyChecking=no root#$IP <<EOF &
It's just confusing because of the here-doc, but the & metacharacter still parses correctly on my system. Try it.
Also, rather than quoting all your options in one string and then parsing them back out to an array, why not just simplify the whole thing and let them come in as separate arguments? Call it as
./vmSetup.sh 1 2 3 # NOT "1 2 3" with quotes
and the loop becomes just
for i in "$#" # properly quoted, though wouldn't matter for 1 2 3
This whole thing seems a lot simpler and easier to maintain.
Another option, which is what I would do: create a file that is a list of the DNS/IP addresses you need, then pass that file as the lone argument.
#!/bin/bash
while read -r addr || [[ -n "$addr" ]]
do echo "Setting-Up VM $addr"
sshpass -p "root12" ssh -tt -o StrictHostKeyChecking=no root#$addr <<EOF &
pwd
nohup yes | /etc/rc.d/init.d/lifconfig
su tarts
nohup yes | vncserver
sleep 10
exit
exit
EOF
done < "$1"
Better, add valid error checking first to make sure the file exists and is readable, etc, but as a simple case, this should work.
For even better, cleaner, safer code, read https://mywiki.wooledge.org/BashFAQ/001 and follow those suggestions. :)
If ./vmSetup.sh 1 works as expected, these should work:
parallel -j8 ./vmSetup.sh {} ::: 1 2 3 ... 100
seq 100 | parallel -j8 ./vmSetup.sh

How to pass IF statement into SSH in UNIX?

I have the following bash script:
#!/bin/bash
set command "pgrep -x 'gedit' "
ssh -t test#192.168.94.139 $command
Now, I want to include this as well in the other device:
if pgrep -x "gedit" > /dev/null
then
echo "Running"
else
echo "Not Running"
fi
How can I make the IF Statement run on the other device? I wasn't able to include it in the ssh.
I tried this:
set command "pgrep -x 'gedit' "
ssh -t test#192.168.94.139 '
if pgrep -x "gedit" > /dev/null
then
echo "Running"
else
echo "Not Running"
fi'
But it didn't work! maybe because there is no command at the beginning?
Thanks.
Invoke bash with heredoc:
ssh -t test#192.168.94.139 bash <<EOF
if pgrep -x "gedit" > /dev/null
then
echo "Running"
else
echo "Not Running"
fi
EOF

Linux Script to check if process is running and act on the result

I have a process that fails regularly & sometimes starts duplicate instances..
When I run:
ps x |grep -v grep |grep -c "processname"
I will get:
2
This is normal as the process runs with a recovery process..
If I get
0
I will want to start the process
if I get:
4
I will want to stop & restart the process
What I need is a way of taking the result of ps x |grep -v grep |grep -c "processname"
Then setup a simple 3 option function
ps x |grep -v grep |grep -c "processname"
if answer = 0 (start process & write NOK & Time to log /var/processlog/check)
if answer = 2 (Do nothing & write OK & time to log /var/processlog/check)
if answer = 4 (stot & restart the process & write NOK & Time to log /var/processlog/check)
The process is stopped with
killall -9 process
The process is started with
process -b -c /usr/local/etc
My main problem is finding a way to act on the result of ps x |grep -v grep |grep -c "processname".
Ideally, I would like to make the result of that grep a variable within the script with something like this:
process=$(ps x |grep -v grep |grep -c "processname")
If possible.
Programs to monitor if a process on a system is running.
Script is stored in crontab and runs once every minute.
This works with if process is not running or process is running multiple times:
#! /bin/bash
case "$(pidof amadeus.x86 | wc -w)" in
0) echo "Restarting Amadeus: $(date)" >> /var/log/amadeus.txt
/etc/amadeus/amadeus.x86 &
;;
1) # all ok
;;
*) echo "Removed double Amadeus: $(date)" >> /var/log/amadeus.txt
kill $(pidof amadeus.x86 | awk '{print $1}')
;;
esac
0 If process is not found, restart it.
1 If process is found, all ok.
* If process running 2 or more, kill the last.
A simpler version. This just test if process is running, and if not restart it.
It just tests the exit flag $? from the pidof program. It will be 0 of process is running and 1 if not.
#!/bin/bash
pidof amadeus.x86 >/dev/null
if [[ $? -ne 0 ]] ; then
echo "Restarting Amadeus: $(date)" >> /var/log/amadeus.txt
/etc/amadeus/amadeus.x86 &
fi
And at last, a one liner
pidof amadeus.x86 >/dev/null ; [[ $? -ne 0 ]] && echo "Restarting Amadeus: $(date)" >> /var/log/amadeus.txt && /etc/amadeus/amadeus.x86 &
This can then be used in crontab to run every minute like this:
* * * * * pidof amadeus.x86 >/dev/null ; [[ $? -ne 0 ]] && echo "Restarting Amadeus: $(date)" >> /var/log/amadeus.txt && /etc/amadeus/amadeus.x86 &
cccam oscam
I adopted the #Jotne solution and works perfectly! For example for mongodb server in my NAS
#! /bin/bash
case "$(pidof mongod | wc -w)" in
0) echo "Restarting mongod:"
mongod --config mongodb.conf
;;
1) echo "mongod already running"
;;
esac
I have adopted your script for my situation Jotne.
#! /bin/bash
logfile="/var/oscamlog/oscam1check.log"
case "$(pidof oscam1 | wc -w)" in
0) echo "oscam1 not running, restarting oscam1: $(date)" >> $logfile
/usr/local/bin/oscam1 -b -c /usr/local/etc/oscam1 -t /usr/local/tmp.oscam1 &
;;
2) echo "oscam1 running, all OK: $(date)" >> $logfile
;;
*) echo "multiple instances of oscam1 running. Stopping & restarting oscam1: $(date)" >> $logfile
kill $(pidof oscam1 | awk '{print $1}')
;;
esac
While I was testing, I ran into a problem..
I started 3 extra process's of oscam1 with this line:
/usr/local/bin/oscam1 -b -c /usr/local/etc/oscam1 -t /usr/local/tmp.oscam1
which left me with 8 process for oscam1. the problem is this..
When I run the script, It only kills 2 process's at a time, so I would have to run it 3 times to get it down to 2 process..
Other than killall -9 oscam1 followed by /usr/local/bin/oscam1 -b -c /usr/local/etc/oscam1 -t /usr/local/tmp.oscam1, in *)is there any better way to killall apart from the original process? So there would be zero downtime?
If you changed awk '{print $1}' to '{ $1=""; print $0}' you will get all processes except for the first as a result. It will start with the field separator (a space generally) but I don't recall killall caring. So:
#! /bin/bash
logfile="/var/oscamlog/oscam1check.log"
case "$(pidof oscam1 | wc -w)" in
0) echo "oscam1 not running, restarting oscam1: $(date)" >> $logfile
/usr/local/bin/oscam1 -b -c /usr/local/etc/oscam1 -t /usr/local/tmp.oscam1 &
;;
2) echo "oscam1 running, all OK: $(date)" >> $logfile
;;
*) echo "multiple instances of oscam1 running. Stopping & restarting oscam1: $(date)" >> $logfile
kill $(pidof oscam1 | awk '{ $1=""; print $0}')
;;
esac
It is worth noting that the pidof route seems to work fine for commands that have no spaces, but you would probably want to go back to a ps-based string if you were looking for, say, a python script named myscript that showed up under ps like
root 22415 54.0 0.4 89116 79076 pts/1 S 16:40 0:00 /usr/bin/python /usr/bin/myscript
Just an FYI
The 'pidof' command will not display pids of shell/perl/python scripts. So to find the process id’s of my Perl script I had to use the -x option i.e. 'pidof -x perlscriptname'
I cannot get case to work at all.
Heres what I have:
#! /bin/bash
logfile="/home/name/public_html/cgi-bin/check.log"
case "$(pidof -x script.pl | wc -w)" in
0) echo "script not running, Restarting script: $(date)" >> $logfile
# ./restart-script.sh
;;
1) echo "script Running: $(date)" >> $logfile
;;
*) echo "Removed duplicate instances of script: $(date)" >> $logfile
# kill $(pidof -x ./script.pl | awk '{ $1=""; print $0}')
;;
esac
rem the case action commands for now just to test the script. the above pidof -x command is returning '1', the case statement is returning the results for '0'.
Anyone have any idea where I'm going wrong?
Solved it by adding the following to my BIN/BASH Script:
PATH=$PATH:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
In case you're looking for a more modern way to check to see if a service is running (this will not work for just any old process), then systemctl might be what you're looking for.
Here's the basic command:
systemctl show --property=ActiveState your_service_here
Which will yield very simple output (one of the following two lines will appear depending on whether the service is running or not running):
ActiveState=active
ActiveState=inactive
And if you'd like to know all of the properties you can get:
systemctl show --all your_service_here
If you prefer that alphabetized:
systemctl show --all your_service_here | sort
And the full code to act on it:
service=$1
result=`systemctl show --property=ActiveState $service`
if [[ "$result" == 'ActiveState=active' ]]; then
echo "$service is running" # Do something here
else
echo "$service is not running" # Do something else here
fi
If you are using CentOS, no need to write a script and set cron job. Here is one of the smartest ways to ensure systemd services restart on failure.
Make following changes to /usr/lib/systemd/system/mariadb.service
Then under the [Service] section in the file, add the following 2 lines:
Restart=always
RestartSec=3
After saving the file we need to reload the daemon configurations to ensure systemd is aware of the new file
systemctl daemon-reload
Read the following link for the complete steps -
https://jonarcher.info/2015/08/ensure-systemd-services-restart-on-failure/

need a restart server script in 1 hour if not stopped

I am working on a remote servers network setup.
What I need is a script that will rename the "/etc/network/interfaces" file and then restart the computer. The renaming I got but what I don't get is how i can terminate this script in case I don't need it.
See if everything works out fine I like to issue a stop command that will terminate this script, so that the server doesn't restart.
So here is what I got so far. the issues are:
It doesn't return the prompt
The stop command doesn't work. It doesn't get the pid file for some reason. It returns "rm: missing operand" although the echo tells me that the pid file is called "start.pid" and it is present in the /tmp folder
Any ideas?
#! /bin/sh
PATH=/sbin:/usr/sbin:/bin:/usr/bin
. /lib/lsb/init-functions
case "$1" in
start)
;;
export PIDFILE=/var/run/${1}.pid
ps -fe | grep ${1} | head -n1 | cut -d" " -f 6 > ${PIDFILE}
sleep 30 #3600
log_action_msg "WARNING: Will in 60 sec rename /etc/network/interfaces and then restart"
sleep 30# 60
SUFFIX=$(date +%s)
#cp /etc/network/interfaces /etc/network/interfaces.$SUFFIX
cp /tmp/interfaces /etc/network/interfaces.$SUFFIX
sleep 1
#cp /etc/network/interfaces.org /tmp/interfaces
cp /tmp/interfaces.org /tmp/interfaces
sleep 1
#reboot -d -f -i
;;
stop)
if [ -f ${PIDFILE} ]; then
rm ${PIDFILE}
fi
exit 0
;;
*)
echo "Usage: $0 start|stop" >&2
exit 3
;;
esac
Usually this is done using a 'pid-file' - a predetermined file that holds the process identifier of the currently running process. That way if it is called and told to stop, it looks up the pid-file and uses the kill command to send a signal to the currently running process.
There is another benefit of this as well - if you check for the existence of a pid-file (and the existence of that process) when the script is told to start, you can prevent accidentally starting the script twice, which would make stopping both instances problematic.
The stop action can create a file do.not.restart.server in an appropriate location.
The start action can be modified to check whether the do.not.restart.server file exists, and avoid restarting the server if it is. It can/should probably remove the file for future restarts - or maybe it should remove it before it goes to sleep.
Okay, here is a working script, it does what I need. The only improvement I could still wish for is how to return the prompt from the sleep command.
The functionality is there so I am posting it in case others needed as well.
Thanks Dan and Jonathan Leffler for your help and ideas.
#! /bin/sh
PATH=/sbin:/usr/sbin:/bin:/usr/bin
. /lib/lsb/init-functions
export PIDFILESTART=/tmp/network-safty-restart-start.pid
export PIDFILESTOP=/tmp/network-safty-restart-stop.pid
#export FILE=/etc/network/interfaces
export FILE=/tmp/interfaces
case "$1" in
start)
if [ -f ${PIDFILESTART} ]; then
rm ${PIDFILESTART}
fi
if [ -f ${PIDFILESTOP} ]; then
rm ${PIDFILESTOP}
fi
ps -fe | grep ${1} | head -n1 | cut -d" " -f 6 > ${PIDFILESTART}
sleep 3600
log_action_msg "WARNING: Will in 60 sec rename ${FILE} and then restart"
sleep 60
if ! [ -f ${PIDFILESTOP} ]; then
log_action_msg "Restarting NOW"
SUFFIX=$(date +%s)
cp ${FILE} ${FILE}.${SUFFIX}
sleep 1
cp ${FILE}.org ${FILE}
sleep 1
reboot -d -f -i
else
rm ${PIDFILESTOP}
log_action_msg "NOT Restaring as you wish"
fi
;;
stop)
if [ -f ${PIDFILESTART} ]; then
rm ${PIDFILESTART}
ps -fe | grep ${1} | head -n1 | cut -d" " -f 6 > ${PIDFILESTOP}
log_action_msg "Terminating restart script"
fi
log_action_msg "Terminated restart script"
exit 0
;;
*)
echo "Usage: $0 start|stop" >&2
exit 3
;;
esac

Resources