I wanted to autostart and stop a container in Proxmox, this container is a “Torrent Box”, I must note that this is for sharing ISO images of open-source operating systems like Proxmox and Ubuntu as well as downloading any that I need, but it will run overnight from 11pm to 6am. The struggle was that it is easy to start a container using the PCT command in a terminal, but if you put this in your crontab and the container is already running then it will throw out an error message, so I needed a script that would check to see if it’s running or not. I also wanted to know if it worked and output to a log that I can read at a later time.
I won’t bore you with what I went through in detail, but I will say, I had to create an if function to test if the container was running or not, then I could create a function that would start or stop the container. Instead of building the logfile into the script, I cheated and added it to the crontab using the (>) output command.
Here is my code:
#!/bin/bash
# vm to run on not this only runs on containers not virtual machines
vmid=301
# predefined functions for timestamp, starting and stopping vm:
function datetime {
date '+%T_%d-%m-%y'
}
function datetime {
date +"%T_%d-%m-%y"
}
function startvm {
/usr/sbin/pct start $vmid
}
function stopvm {
/usr/sbin/pct stop $vmid
}
# show in output whne started:
printf " `echo "Script Started:" ` `datetime` \n "
# check status of vm:
status=$(/usr/sbin/pct status $vmid)
# if up then stop, if down then start:
if [ "$status" == "status: stopped" ]; then
printf " `datetime ` `echo "$vmid, Not running, Starting" ` \n "
startvm
printf " `datetime ` `echo "Started" ` \n "
elif [ "$status" == "status: running" ]; then
printf " `datetime ` `echo "VM $vmid Running, Stopping" ` \n "
stopvm
printf " `datetime ` `echo "Stopped" ` \n "
fi
# pause for results
sleep 10
printf " `datetime ` `echo "Done" ` \n "
My crontab looks like this:
# Start and stop Torrent Server 11pm to 6am.
0 23 * * * /root/startvm.sh > /var/log/script_logs
10 6 * * * /root/startvm.sh > /var/log/script_logs
I hope this helps someone!
Chris!
Comments are closed