开发者

Creating cron entry on server using ssh login within shell script

I need to upload a file (bash script) to a remote sever. I use the scp command. After the file has been copied to the remote server I want to create a cron entry in the crontab file on the remote server. However, the file up开发者_如何学Pythonload and writing the cron entry need to occur within a bash shell script so that I only need to execute the script on my local machine and the script is copied to the remote host and the cron entry is written to the crontab.

Is there a way that I can use an ssh command, within the script, that logs me into the remote server, opens the crontab file and writes the cron entry.

Any help is very welcome


I would:

  1. extract the user's crontab with crontab -l > somefile
  2. modify that file with the desired job
  3. import the new crontab with crontab somefile


I just did something like this where I needed to create a multiline line crontab on a remote machine. By far the simplest solution was to pipe the content to the remote crontab command through ssh like this:

echo "$CRON_CONTENTS" | ssh username@server crontab 


mailo seemed almost right, but the command would be the second argument to the ssh command, like this:

ssh username@server 'echo "* * * * * /path/to/script/" >> /etc/crontab'

Or if your system doesn't automatically load /etc/crontab you should be able to pipe to the crontab command like this:

ssh username@server 'echo "* * * * * myscript" | /usr/bin/crontab'


Say you want to copy $local to $remote on $host and add an hourly job there to run at 14 past every hour, using a single SSH session;

ssh "$host" "cat >'$remote' && 
    chmod +x '$remote' && 
    ( crontab -l; 
      echo '14 * * * * $remote' ) | crontab" <"$local"

This could obviously be much more robust with proper error checking etc, but hopefully it should at least get you started.

The two keys here are that the ssh command accepts an arbitrarily complex shell script as the remote command, and gets its standard input from the local host.

(With double quotes around the script, all variables will be interpolated on the local host; so the command executed on the remote host will be something like cat >'/path/to/remote' && chmod +x '/path/to/remote' && ... With the single quotes, you could have whitespace in the file name, but I didn't put them in the crontab entry because it's so weird. If you need single quotes there as well, I believe it should work.)


You meant something like

ssh username@username.server.org && echo "* * * * * /path/to/script/" >> /etc/crontab

?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜