[Linux](EN) Modify crontab using ssh
Post about modifying crontab using ssh
Environment and Prerequisite
- Linux
- SSH(OpenSSH)
- crontab
How
crontab
crontab [-u user] file
crontab [-u user] { -l | -r [-f] | -e }
- Give standard input(stdin) or filename after crontab command overwrite crontab content to that standard input(stdin) or file.
crontab -e
cannot be used in ssh command so use above method.- Document says “The first form of this command is used to install a new crontab from some named file or standard input if the pseudo-filename ‘-‘ is given”.
Example
Scenario
- Modify server’s crontab from current computer
Example
- Check crontab content in server
# Check remote crontab
ssh twpower@157.230.234.230 "crontab -l"
0 10 17 * * /home/twpower/simple-script.sh
40 7 * * 1 python /home/twpower/run.py
- Modify crontab content and apply it after copy crontab content to
/tmp
.
# Copy current crontab content to temporary file
ssh twpower@157.230.234.230 "crontab -l > /tmp/tmp-crontab-content"
# Add crontab content to temporary file
# Not only addition but also deletion and modification are possible
# Many variations are possible like using sed, tee or cat
ssh twpower@157.230.234.230 "echo '* * * * 1 python /home/twpower/run.py' >> /tmp/tmp-crontab-content"
# Apply new crontab using temporary file
ssh twpower@157.230.234.230 "crontab /tmp/tmp-crontab-content"
# Remove temporary file
ssh twpower@157.230.234.230 "rm -rf /tmp/tmp-crontab-content"
- Check result
# Check remote crontab
ssh twpower@157.230.234.230 "crontab -l"
0 10 17 * * /home/twpower/simple-script.sh
40 7 * * 1 python /home/twpower/run.py
* * * * 1 python /home/twpower/run.py
Script
- It can be made to script like below.
#!/bin/bash
# Copy current crontab content to temporary file
ssh twpower@157.230.234.230 "crontab -l > /tmp/tmp-crontab-content"
# Add crontab content to temporary file
# Not only addition but also deletion and modification are possible
# Many variations are possible like using sed, tee or cat
ssh twpower@157.230.234.230 "echo '* * * * 1 python /home/twpower/run.py' >> /tmp/tmp-crontab-content"
# Apply new crontab using temporary file
ssh twpower@157.230.234.230 "crontab /tmp/tmp-crontab-content"
# Remove temporary file
ssh twpower@157.230.234.230 "rm -rf /tmp/tmp-crontab-content"