Creating cron entry on server using ssh login inside shell script

I need to upload a file (bash script) to a remote server. I am using 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, downloading the file and writing the cron entry should take place in the shell of the bash script, so I only need to execute the script on my local computer, and the script will be copied to the remote host, and the cron entry is written to crontab.

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

Any help is greatly appreciated.

+4
source share
5 answers

I'd:

  • crontab -l > somefile crontab user with crontab -l > somefile
  • change this file with the desired task
  • import new crontab using crontab somefile
+7
source

I just did something like this where I needed to create a multi-line crontab line on a remote machine. The simplest solution was to pass the contents to the remote crontab command via ssh as follows:

 echo "$CRON_CONTENTS" | ssh username@server crontab 
+1
source

mailo seemed almost correct, but the command would be the second argument to the ssh command, for example:

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

Or, if your system does not automatically load / etc / crontab, you should be able to connect to the crontab command as follows:

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

Suppose you want to copy $local to $remote on $host and add an hourly job that should run 14 times per hour using one SSH session;

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

This can obviously be much more reliable with correct error checking, etc., but hopefully it should at least get started.

Two keys are here: the ssh command accepts an arbitrarily complex shell script as a remote command and receives 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 look like cat >'/path/to/remote' && chmod +x '/path/to/remote' && ... With single quotes, you can have spaces in the file name, but I did not put them in the crontab entry, because it is so strange. If you need single quotes too, I think it should work.)

0
source

Did you mean something like

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

?

-1
source

Source: https://habr.com/ru/post/1340231/


All Articles