我尝试设置一个cron作业rsync远程文件(包含根级文件)到我的本地服务器,如果我在shell中运行命令,它的工作原理。但是如果我在Python中运行它,我会遇到奇怪的命令找不到错误:
如果在shell中运行它,这是有效的:
rsync -ave ssh --rsync-path='sudo rsync' --delete [email protected]:/tmp/test2 ./test
但是这个Python脚本没有:
#!/usr/bin/python
from subprocess import call
....
for src_dir in backup_list:
call(["rsync", "-ave", "ssh", "--rsync-path='sudo rsync'", "--delete", src_host+src_dir, dst_dir])
它失败了:
local server:$ backup.py
bash: sudo rsync: command not found
rsync: connection unexpectedly closed (0 bytes received so far) [Receiver]
rsync error: remote command not found (code 127) at io.c(226) [Receiver=3.1.0]
...
它很可能是间距错误或小的东西,我调试命令的方式是确保打印输出。虽然子进程更好,但OS.system是一个很好的选择。我不是在我的计算机上测试它,但你可以设置你的子进程,或使用这个例子。这是假设你在Linux或Mac上。
import os
cmd = ('rsync -ave --delete root' +str(src_host) + str(src_directory) + '' + str(dst_dir)) #variable you can call anytime
os.system(cmd) # actually performs the command
print x # how to test and make sure
当shell将一个长字符串拆分为参数时,需要在"--rsync-path='sudo rsync'"
中使用类似于空格的参数引用,以避免将rsync
视为单独的参数。在你的call()
中,你提供了各个参数,因此不会执行将字符串拆分为参数。使用您的代码,引号最终作为传递给rsync
的参数的一部分。放下它们吧。这是一个传递给call()
的列表的工作示例,用于非常类似的rsync
调用:
['rsync',
'-arvz',
'-delete',
'-e',
'ssh',
'--rsync-path=sudo rsync',
'192.168.0.17:/remote/directory/',
'/local/directory/']