Python 读取远程根级文件时出现 rsync 错误
Python rsync error in reading remote root-level files
我尝试设置一个 cron 作业以将远程文件(包含根级文件)rsync 到我的本地服务器,如果我 运行 shell 中的命令有效。但是如果我在 Python 中 运行 这个,我会遇到奇怪的命令未找到错误:
如果 运行 它在 shell:
rsync -ave ssh --rsync-path='sudo rsync' --delete root@192.168.1.100:/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/']
我尝试设置一个 cron 作业以将远程文件(包含根级文件)rsync 到我的本地服务器,如果我 运行 shell 中的命令有效。但是如果我在 Python 中 运行 这个,我会遇到奇怪的命令未找到错误:
如果 运行 它在 shell:
rsync -ave ssh --rsync-path='sudo rsync' --delete root@192.168.1.100:/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/']