Reputation: 189
I am having a crontab entry in my Python code describing which script should be scheduled in the UNIX remote server at the specified time.
I am writing a Python script which will connect to the ssh using Paramiko, it will go to the specified crontab file path in the remote server -> open the crontab file -> add the crontab entry specified in the Python script at the end of the file (on the new line) -> save & exit the crontab file.
Please let me know how I can achieve this.
P.S. : I already know how to connect to the server using Paramiko. Just stucked at the file handling part in the remote server.
Upvotes: 0
Views: 7461
Reputation: 116
crontab -l 2>/dev/null| cat - <(echo "your new crontab entry here") | crontab -
crontab -l
Outputs the current crontab to stdout.
2>/dev/null
[Optional] Supresses error messages from crontab -l. You'll get an error message if there is no crontab entry for the user. But that's not a problem.
cat - <(echo "your crontab entry here")
The -
takes the input from the pipe (crontab -l) and uses it as the first thing to cat. Then the rest appends your new crontab entry to stdout. The <() syntax takes the output of the command inside and stores it in a temporary file.
crontab -
This sets the crontab entry to the stdin (which, thanks to the pipe, is all the stdout from the previous commands.)
Edit: It looks like you'll need to wrap the command with bash -c
in order to get the pipes to work. See this stackoverflow entry.
Or, you can send a series of commands to paramiko. Just beware of concurrency.
crontab -l > /tmp/current.cron
echo "your crontab entry here" >> /tmp/current.cron
crontab /tmp/current.cron
Another alternative is:
crontab <(cat <(crontab -l 2>/dev/null) <(echo "your new crontab entry"))
Upvotes: 2
Reputation: 3228
I don't know exactly how Paramiko works but if you could use shell you can just simply execute:
echo "new line" >> cron_file
This command will add a string new line
as a new line to the file cron_file
.
Upvotes: 0