Bash: How to manage crontabs remotely

Working with crontabs in remote servers usually takes place with the following procedure, Assuming that you follow bad practices like me…

Bash: How to manage crontabs remotely
Photo by Erik Mclean on Unsplash

Working with crontabs in remote servers usually takes place with the following procedure, Assuming that you follow bad practices like me, first login to the remote server as root and then submitting crontab -e , since this is a very standard procedure would be nice to do this shorter? yes there is lets see how!

I love one-liners

using this one-liner ssh -t root@x.x.x.x 'crontab -e' allows you to do this at once, -t parameter allocates a terminal which is needed to use it with with vim that is used to edit the crontab, ok now we have a solution but would be nicer to enter only the needed parameters in order to save time and effort? we can!

I also love shell functions

Open .bashrc or .zshrc depending what shell you use and enter the following at the end of your file

rcron() { 
    if [ $# -eq 0 ] || [ $# -gt 2 ]; then 
        echo "Usage: rcront [username] <ip>" 
        return 1 
    fi 
 
    local username="root" 
    local ip 
 
    if [ $# -eq 1 ]; then 
        ip="$1" 
    else 
        username="$1" 
        ip="$2" 
    fi 
 
    ssh -t "${username}@${ip}" 'crontab -e' 
}

Then reload your rc file by entering

source ~/.bashrc

or the following if you use zsh (probably when you use a Mac)

source ~/.zshrc

How to use it

Assume that you want to edit the crontab of root of server01, entering the following will connect to server01 as root and will open the cron editor

rcron server01

Now assume that you want to edit the crontab of user user1 of server01, entering the following will do the job

rcron user1 server01

Conclusion

Using one-liners and functions can automate large part for your daily effort! learn them and you will have the admiration of every Linux user in the office! or at least you can brag to the Windows admins how easier is to manage Linux servers!