我试图在远程部署的嵌入式Linux设备上获取一个python脚本来执行scp命令。执行命令很简单,但是如果目标服务器没有列在“known_hosts”文件中,scp会抛出一个需要与之交互的警告。我的头撞了好几天,我都解决不了两个问题。在
首先,我无法从子进程获取响应的非阻塞读取,以使其正常工作。在下面的代码中,选择always returns([],[],[]),即使我知道我可以从stderr读取(假设生成了可信主机文件警告)。在cmdString = 'scp user@remote.com:file localFile -i ~/.ssh/id_rsa'
process = subprocess.Popen(shlex.split(cmdString), shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
while(process.poll() is None):
readable, writable, exceptional = select.select([process.stdout], [], [process.stderr], 1)
if not (readable or writable or exceptional):
# Always hits this condition, although adding an "os.read(...)" here
# will return the error prompt from process.stderr.
print "timeout condition"
else:
# Never makes it here
for e in exceptional:
stderr = os.read(process.stderr.fileno(), 256)
print stderr
for r in readable:
stdout = os.read(process.stdout.fileno(), 256)
print stdout
第二,我无法通过输入管道提供输入,从而使子进程超出警告。以下代码从中读取警告代码过程标准但一直挂起,直到我在终端中点击{enter}。我尝试过发送“n”、“n\n”和“\n”,但是没有任何一个会导致子进程继续执行(尽管手动输入时所有3个模式都可以工作)。在
^{pr2}$
最后,这有关系吗?我最初开始研究子进程和管道,因为我使用的是操作系统(cmdString)“它阻止了我的线程并迫使我处理该问题。现在我使用的是子进程,直接启动命令并让它成功还是失败是不好的?失败的子进程最终会消亡,还是最终会在运行几十个或数百个隐藏的scp尝试,但等待用户输入的地方结束?在
谢谢!在