简体   繁体   中英

How to use ssh to schedule an 'at' job or a 'cron job' on a linux server from a python program on Windows client

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM