Linux Script to check a process is up or not - linux

I have a server Application which holds 1500 process id, I need a shell Script which checks for every hour whether the process is up, if not start the process using "dsmc -u xxxx -p **" if it is not started send a mail to my gmail(xxx#gmail.com). here is the code how can i send a mail to my gmail account.
if pidof -s vsftpd = /dev/null; then
echo 'ftp is stopped'
sudo /etc/init.d/vsftpd restart
else
echo "The FTP server is Down" | mail -s "Ftp Server is Down" abcd#example.com
fi
I don't get mail to my Gmail Account.
Reference: http://rtcamp.com/wordpress-nginx/tutorials/linux/ubuntu-postfix-gmail-smtp/

to write your script you probably would want to investigate the following functions and their associated man pages
ps
pgrep
ptree
mail

The script part is easy to do. Troubleshooting the mail however is not. I would recommend running the script in screen (screen -d -m /bin/bash "test.sh"), detaching the screen (ctrl -a + d) then killing the process (/etc/init.d/vsftp stop), waiting 1 minute, and reattach the screen (screen -r). That will provide you the error with mail you can troubleshoot.
The following script will monitor your service for you.
#!/bin/bash
process="vsftp"
while true ; do
until [ ! $(pgrep $process) ]; do
sleep 1 #The number or minutes to wait until next check
done
#If process is not found do the following
/etc/init.d/$process start > /dev/null #Run as root because sudo requires password
if [ $? != 1 ]; then
echo "The FTP server was restarted" | mail -s "Ftp Server $process was restarted" abcd#example.com
else
echo "The FTP server could not restart" | mail -s "Ftp Server $process is down" abcd#example.com
sleep 1
exit 0;
fi
done
Hope this helps and good luck.

We can do the script with ps -ef
try,
# cat vsftpd.sh
#!/bin/bash
/bin/ps -ef | grep vsftpd > /dev/null 2>&1
if [ $? -ne 0 ]
then
/etc/init.d/vsftpd restart > /dev/null 2>&1
/bin/mail -s "FTP service is RESTARTED now" abcd#example.com
else
sleep 0
fi
cron:
* * * * * /bin/sh /path/to/vsftpd.sh > /dev/null 2>&1

Related

How to fix crontab issue with end of file unexpected in script

I wrote a script to check for some services if they are active or not and restart the services.
The script works when ran manually but when added to crontab it does not work, when I check the logs I get
/bin/sh: 1: Syntax error: end of file unexpected
This is my script
#!/bin/bash
echo "Checking odoo services"
sudo service odoo13 status | grep 'active (running)' > /dev/null 2>&1
if [ $? != 0 ]
then
echo "Odoo not running restarting..."
sudo service odoo13 restart > /dev/null
fi
echo "Checking nginx services"
sudo service nginx status | grep 'active (running)' > /dev/null 2>&1
if [ $? != 0 ]
then
echo "Nginx inactive restarting"
sudo service nginx restart > /dev/null
fi
I set the crontab to run every minute
*/1 * * * * /opt/check_services.sh > /dev/null 2>
I do not know, what seems to be the issue?
So I figured it out
instead of #!/bin/bash I used #!/usr/bin/env bash
strange isn't it?

Bash Script: Apache Server is running or not

I'm trying to achieve the following steps using bash script:
1) Check the status of Apache Server.
2) If it is up and running, do nothing. If it is not, then go to step 3.
3) If server is not running, then send a failure email first and restart the server
4) After restarting, check the status again, and send a confirmation email
Here is my code:
#checking if Apache is running or not
ps auxw | grep apache2 | grep -v grep > /dev/null
if [ $? != 0 ]
then
mailx -s "Apache web server is down, Trying auto-restart" -$
# web server down, restart the server
sudo /etc/init.d/apache2 restart > /dev/null
sleep 10
#checking if apache restarted or not -- This is not working
ps auxw | grep apache2 | grep -v grep > /dev/null
if [ $? = 0 ]
then
mailx -s "Apache restarted succesfully" -r "$SENDEREMAIL" "$NOTIFYEMAIL" < /$
else
mailx -s "Restart Failed, try restarting manually" -r "$SENDEREMAIL" "$NOTIFYEMAIL" <$
fi
fi
The code is working properly till step 3, and failing/not working on step 4 i.e. script is unable to check the status of the server after restart and sending a confirmation email.
Can someone please let me know where I'm going wrong.
Try this:
#checking if Apache is running or not
if ! pidof apache2 > /dev/null
then
mailx -s "Apache web server is down, Trying auto-restart"
# web server down, restart the server
sudo /etc/init.d/apache2 restart > /dev/null
sleep 10
#checking if apache restarted or not
if pidof apache2 > /dev/null
then
message="Apache restarted successfully"
else
message="Restart Failed, try restarting manually"
fi
mailx -s "$message" -r "$SENDEREMAIL" "$NOTIFYEMAIL"
fi
Note: every mailx line had a trailing -$, < /$, or <$ -- these looked like typos and were deleted.

Working around sudo in shell script child process

So the reason I am asking this is because I'm running two programs simultaneously that are persistent, on the child process a programm is running that requires sudo rights.
#!/bin/bash
echo "Name the file:"
read filename
while [[ 1 -lt 2 ]]
do
if [ -f /home/max/dump/$filename.eth ]; then
echo "File already exist."
read filename
else
break
fi
done
#Now calling a new terminal for dumping
gnome-terminal --title="tcpdump" -e "sh /home/max/dump/dump.sh $filename.eth"
ping -c 1 0 > /dev/null **Waiting for tcpdump to create file**
#Packet analysis program is being executed
Script dump.sh
#!/bin/bash
filename=$1
echo password | sudo tcpdump -i 2 -s 60000 -w /home/max/dump/$filename -U
host 192.168.3.2
#Sudo still asks me for my password though password is piped into stdin

Crontab executing script differently

I have a script that checks if MySQL service is running on my Linux server.
If I run the script manually it works fine, but when crontab runs the script it gets different results..
This is my script:
#! /bin/sh
TODAY=$(/bin/date)
UP=$(/sbin/service mysql status| /bin/grep 'SUCCESS' | /usr/bin/wc -l);
if [ "$UP" -ne 1 ];
then
echo "mysql not working, Date: $TODAY" >> /scripts/sql_log.txt;
sudo /bin/mail -s "MySql is DOWN" mail#mail.com < /dev/null
sudo /sbin/service mysql start
else
echo "mysql is working, Date: $TODAY" >> /scripts/sql_log.txt;
fi
I am using the full path of the commands..the only part that I do not understand 100% is:
if [ "$UP" -ne 1 ];
What is this -ne 1?
So in this case MySQL is running:
If I run the script manually it writes that MySQL is working in the log file.
But Crontab just write that MySQL is not running in the log file (even if it is running) and it does not send any mail or something
If mysql service is stopped and I run the script manually, it send me an email and start the service as it should...
Any idea?
Now it works..looks like that the problem was caused because I did not write the full path of the command..This is the script that I am using now and it is working:
#! /bin/sh
UP=$(/sbin/service mysql status| /bin/grep 'SUCCESS' | /usr/bin/wc -l);
if [ "$UP" -ne 1 ];
then
sudo /bin/mail -s "MySql is DOWN" mail#mail.com < /dev/null
sudo /sbin/service mysql start
fi

How to set up an automatic (re)start of a background ssh tunnel

I am a beginner user of linux, and also quite newbie at ssh and tunnels.
Anyway, my goal is to maintain a ssh tunnel open in background.
In order to do that, I wrote the following batch that I then added into crontab (the batch is automatically processed every 5 minutes during workdays and from 8am to 9pm).
I read in some other thread in stackoverflow that one should use autossh that will ensure the ssh will always be ok through a recurrent check. So did I....
#!/bin/bash
LOGFILE="/root/Tunnel/logBatchRestart.log"
NOW="$(date +%d/%m/%Y' - '%H:%M)" # date & time of log
if ! ps ax | grep ssh | grep tunnelToto &> /dev/null
then
echo "[$NOW] ssh tunnel not running : restarting it" >> $LOGFILE
autossh -f -N -L pppp:tunnelToto:nnnnn nom-prenom#193.xxx.yyy.zzz -p qqqq
if ! ps ax | grep ssh | grep toto &> /dev/null
then
echo "[$NOW] failed starting tunnel" >> $LOGFILE
else
echo "[$NOW] restart successfull" >> $LOGFILE
fi
fi
My problem is that sometimes the tunnel stops working, although every thing looks ok (ps ax | grep ssh > the result shows the two expected tasks : autossh main task and the ssh tunnel itself). I actually know about the problem cause the tunnel is used by a third party software that triggers an error as soon as the tunnel is no more responding.
SO I am wondering how I should improve my batch in order It will be able to check the tunnel and restart it if it happens to be dead. I saw some ideas in there, but it was concluded by the "autossh" hint... which I already use. Thus, I am out of ideas... If any of you have, I'd gladly have a look at them!
Thanks for taking interest in my question, and for your (maybe) suggestions!
Instead of checking the ssh process with ps you can do the following trick
create script, that does the following and add it to your crontab via crontab -e
#!/bin/sh
REMOTEUSER=username
REMOTEHOST=remotehost
SSH_REMOTEPORT=22
SSH_LOCALPORT=10022
TUNNEL_REMOTEPORT=8080
TUNNEL_LOCALPORT=8080
createTunnel() {
/usr/bin/ssh -f -N -L$SSH_LOCALPORT:$REMOTEHOST:SSH_REMOTEPORT -L$TUNNEL_LOCALPORT:$REMOTEHOST:TUNNEL_REMOTEPORT $REMOTEUSER#$REMOTEHOST
if [[ $? -eq 0 ]]; then
echo Tunnel to $REMOTEHOST created successfully
else
echo An error occurred creating a tunnel to $REMOTEHOST RC was $?
fi
}
## Run the 'ls' command remotely. If it returns non-zero, then create a new connection
/usr/bin/ssh -p $SSH_LOCALPORT $REMOTEUSER#localhost ls >/dev/null 2>&1
if [[ $? -ne 0 ]]; then
echo Creating new tunnel connection
createTunnel
fi
In fact, this script will open two ports
port 22 which will be used to check if the tunnel is still alive
port 8080 which is the port you might want to use
Please check and send me further questions via comments
(I add this as an answer since there is not enough room for it un a comment)
Ok, I managed to make the batch run to launch the ssh tunnel (I had to specify my hostname instead of localhost in order it could be triggered) :
#!/bin/bash
LOGFILE="/root/Tunnel/logBatchRedemarrage.log"
NOW="$(date +%d/%m/%Y' - '%H:%M)" # date et heure du log
REMOTEUSER=username
REMOTEHOST=remoteHost
SSH_REMOTEPORT=22
SSH_LOCALPORT=10022
TUNNEL_REMOTEPORT=12081
TUNNEL_SPECIFIC_REMOTE_PORT=22223
TUNNEL_LOCALPORT=8082
createTunnel() {
/usr/bin/ssh -f -N -L$SSH_LOCALPORT:$REMOTEHOST:$SSH_REMOTEPORT -L$TUNNEL_LOCALPORT:$REMOTEHOST:$TUNNEL_REMOTEPORT $REMOTEUSER#193.abc.def.ghi -p $TUNNEL_SPECIFIC_REMOTE_PORT
if [[ $? -eq 0 ]]; then
echo [$NOW] Tunnel to $REMOTEHOST created successfully >> $LOGFILE
else
echo [$NOW] An error occurred creating a tunnel to $REMOTEHOST RC was $? >> $LOGFILE
fi
}
## Run the 'ls' command remotely. If it returns non-zero, then create a new connection
/usr/bin/ssh -p $SSH_LOCALPORT $REMOTEUSER#193.abc.def.ghi ls >/dev/null 2>&1
if [[ $? -ne 0 ]]; then
echo [$NOW] Creating new tunnel connection >> $LOGFILE
createTunnel
fi
However, I got some immediate message (below) when the tunnel is running and when cron tries to lauch the batch again... sounds like it cannot listen to it. Also since I need some time to get a proof , I can't say yet it will successfully restart if the tunnel is out.
Here's the response to the second start of the batch.
bind: Address already in use channel_setup_fwd_listener: cannot listen
to port: 10022 bind: Address already in use
channel_setup_fwd_listener: cannot listen to port: 8082 Could not
request local forwarding.

Resources