0

I am attempting to schedule a job to run on a linux server from a python app on Windows 10 by using os.system(). The following code executes but fails to schedule the job.

os.system('ssh myadmin@mnop.com "at 09:00 {}".format("iostat > /home/myadmin/t.txt")')
os.system('ssh myadmin@mnop.com  "crontab 0 9 9 1 * /home/myadmin.msg.sh"')

My objective is to schedule a one time execution. Thanks for suggestion.

Roberto Caboni
  • 7,252
  • 10
  • 25
  • 39
jlar
  • 11

1 Answers1

1

The sole argument to at is the time; it then reads the commands from standard input. Similarly, crontab reads the cron schedule from standard input, not as parameters to the command.

import subprocess

subprocess.run(['ssh', 'myadmin@mnop.com', 'at 09:00'],
    text=True, check=True,
    input="iostat > /home/myadmin/t.txt\n")
subprocess.run(['ssh', 'myadmin@mnop.com', 'crontab'],
    text=True, check=True,
    input='0 9 9 1 * /home/myadmin/msg.sh\n')

Notice that the latter will replace any existing crontab for the user. I fixed the typo you pointed out in a comment.

Notice also how we switch to subprocess.run instead of os.system, as recommended in the documentation for the latter. I refactored to avoid having to use shell=True; perhaps see also Actual meaning of 'shell=True' in subprocess

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • The 'at' solution that you provided works fine. Thank you, tripleee. When executing the 'crontab' solution, I get the following error: CalledProcessError: Command '['ssh', 'myadmin@mnop.com', 'crontab']' returned non-zero exit status 1. (I made a typo on the input. Should be, input='0 9 9 1 * /home/myadmin/msg.sh' – jlar Aug 02 '20 at 00:08
  • Then I guess it gives you an error message telling you what's wrong? You can substantially simplify your troubleshooting by taking out the Python and SSH parts. Try adding a dash, like `crontab -` – tripleee Aug 02 '20 at 09:02
  • I tested on both Linux and macOS and neither of them require a dash with `crontab`. If you are installing a crontab for `root` your syntax is wrong (it requires a fifth field before the command to identify which user to run the job as). – tripleee Aug 02 '20 at 10:19
  • If this is all the code you are running, you really don't need Python here. Using `format` to merge two static strings is decidedly odd but perhaps this is a reduced example from more complex code where these complications make sense. – tripleee Aug 02 '20 at 10:24
  • Both solutions that you provided are now working. The crontab error, "non-zero exit status 1" was resolved by adding a '\n' at the end of the input='0 9 9 1 * /home/myadmin/msg.sh\n' Thanks for your clear instructions. – jlar Aug 03 '20 at 17:55