5

当我运行我的 Python 应用程序(在本地同步远程目录)时,如果包含我的应用程序的目录的名称中有一个或多个空格,我会遇到问题。目录名称出现在 ssh 选项中,例如“ -o UserKnownHostsFile=<path>”和“ -i <path>”。我尝试在生成命令字符串的函数中使用双引号路径,但没有。我也尝试像这样替换空格:path.replace(' ', '\\ '),但它不起作用。请注意,我的代码适用于不带空格的目录名。ssh 返回的错误是“行尾的垃圾”(代码 12) 生成的命令行似乎没问题..

rsync -rztv --delete --stats --progress --timeout=900 --size-only --dry-run \
    -e 'ssh -o BatchMode=yes \
    -o UserKnownHostsFile="/cygdrive/C/Users/my.user/my\ app/.ssh/known_hosts" \
    -i "/cygdrive/C/Users/my.user/my\ app/.ssh/id_rsa"'
    user@host:/home/user/folder/ "/cygdrive/C/Users/my.user/my\ app/folder/"

我究竟做错了什么?谢谢!

4

3 回答 3

5

您是否尝试过将命令构建为参数列表 - 我在为 ssh 连接传递密钥文件时遇到了类似的问题:

command = [
  "rsync",
  "-rztv",
  "--delete",
  "--stats",
  "--progress",
  "--timeout=900",
  "--size-only",
  "--dry-run",
  "-e",
  "ssh -o BatchMode=yes -o UserKnownHostsFile='/cygdrive/C/Users/my.user/my\ app/.ssh/known_hosts' -i '/cygdrive/C/Users/my.user/my\ app/.ssh/id_rsa'",
  "user@host:/home/user/folder/",
  "/cygdrive/C/Users/my.user/my\ app/folder/"
]

sp = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output = sp.communicate()[0]
于 2012-09-12T10:46:13.177 回答
0

为避免转义问题,请使用原始字符串,

raw_string = r'''rsync -rztv --delete --stats --progress --timeout=900 --size-only --dry-run -e 'ssh -o BatchMode=yes -o UserKnownHostsFile="/cygdrive/C/Users/my.user/my app/.ssh/known_hosts" -i "/cygdrive/C/Users/my.user/my app/.ssh/id_rsa"' user@host:/home/user/folder/ "/cygdrive/C/Users/my.user/my app/folder/"'''

sp = subprocess.Popen(raw_string, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output = sp.communicate()[0]
于 2012-07-12T08:42:56.863 回答
0

子命令返回的数据包含空格作为分隔符。尝试更新内部字段分隔符 (IFS) 列表,例如:

# store a copy of the current IFS
SAVEIFS=$IFS;
# set IFS to be newline-only
IFS=$(echo -en "\n\b");

# execute your command(s)
rsync -rztv --delete --stats --progress --timeout=900 --size-only --dry-run -e 'ssh -o BatchMode=yes -o UserKnownHostsFile="/cygdrive/C/Users/my.user/my\ app/.ssh/known_hosts" -i "/cygdrive/C/Users/my.user/my\ app/.ssh/id_rsa"' user@host:/home/user/folder/ "/cygdrive/C/Users/my.user/my\ app/folder/"

# put the original IFS back
IFS=$SAVEIFS;

我没有使用您的命令进行测试,尽管它在我过去尝试过的所有情况下都有效。

于 2012-07-11T15:39:58.557 回答