首页 > 解决方案 > python子进程和wget询问密码

问题描述

我正在运行以下 python 代码:

import subprocess
host = "ftp://localhost:2121"
p = subprocess.Popen(
  ['wget', '-P', '/tmp/output', '-N', '-r', '-l', 'inf', '--ask-password', '--user', 'anonymous', host],
  stdin=subprocess.PIPE)
p.communicate("password\n")
if p.returncode != 0:
    raise RuntimeError('wget command failed with return code: %d' % p.returncode)  

似乎password没有发送到 wget,因为脚本将挂起显示:

Password for user ‘anonymous’: 

按下回车键会导致 wget 退出并返回错误代码“1”

按下键然后按下回车键会导致 wget 按预期开始下载。

ftp 服务器是本地的并且启用了匿名访问。Python 版本为 2.7.8

标签: pythonsubprocess

解决方案


wget 似乎从 tty 而不是 stdin 读取密码。这些不一样!

sudo 命令允许您切换到标准输入

某些程序直接从 /dev/tty 读取,而不是 stdin。例如“密码”。所以很难编写脚本。Expect 是一种解决方法——它可以通过向程序提供输入来欺骗程序:

实现从标准输入读取密码的一种方法是构造一个包含用户和密码的 url:

ftp://user:password@ftp.server.com/link.txt

并使用-l -开关通过标准输入将链接传递给 wget。这是建议here


推荐阅读