Automating cron Service Backup and Restart with Bash
DEVESH NEMADE
2 min read
This script automates the backup, update, and restart process of the cron.jar application on a Linux server. It involves creating a backup of the current JAR file, downloading a new version from a remote SFTP server, stopping the current process, replacing the JAR file, restarting the application, and monitoring its logs.
#!/bin/bash
# Define the remote server's IP, username, and password for SFTP connection
HOST=IP
USER=team
PASSWD=97456321
# Get the process ID (PID) of the currently running `apcron.jar` application
aptpid=ps -ef | grep -v awk | awk -e '/apcron.jar/ { print $2 }'
# Read a name input (for backup directory)
read name
# Create a backup directory using the given name
mkdir /home/gate/backup/$name
# Navigate to the application directory
cd /home/gate/avde/apcron
# Copy the existing JAR file to the backup directory
cp -R apcron.jar /home/gate/backup/$name
# Navigate to the backup directory and list the contents for verification
cd /home/gate/backup/$name
ls -lrth
sleep 2
# Use lftp to connect to the remote SFTP server and download the new `apcron.jar`
cd /home/paygate/avde/apcron/
lftp <<END_SCRIPT
open sftp://$HOST
user $USER $PASSWD
cd /Logs/apcron_jar
get apcron.jar
bye
END_SCRIPT
# Output the PID of the current process
echo $aptpid
sleep 2
# Kill the currently running `apcron.jar` application
kill -9 $aptpid
echo "apcron service is DOWN"
sleep 2
# Switch to the `paygate` user and restart the application
sudo -i -u paygate bash << EOF
source /etc/profile
cd /home/paygate/avde/apcron/
./runapcron.sh
EOF
# Check and output the new PID of the restarted application
aptpid2=ps -ef | grep -v awk | awk -e '/apcron.jar/ { print $2 }'
echo $aptpid2
sleep 2
# Monitor the application logs in real-time
cd /home/paygate/avde/apcron/
tail -f nohup.out
0
Subscribe to my newsletter
Read articles from DEVESH NEMADE directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by