【发布时间】:2015-10-23 15:31:46
【问题描述】:
我需要在 python 中执行这个命令并从键盘输入密码,这是可行的:
import os
cmd = "cat /home/user1/.ssh/id_rsa.pub | ssh user2@host.net \'cat >> .ssh/authorized_keys\' > /dev/null 2>&1"
os.system(cmd)
如您所见,我想通过 ssh 将公钥附加到远程主机。
见这里:equivalent-of-ftp-put-and-append-in-scp 和这里:copy-and-append-files-to-a-remote-machine-cat-error
当然我希望它在没有用户输入的情况下完成我已经尝试过 pexpect 并且我认为命令对它来说很奇怪:
import pexpect
child = pexpect.spawn(command=cmd, timeout=10, logfile=open('debug.txt', 'a+'))
matched = child.expect(['Password:', pexpect.EOF, pexpect.TIMEOUT])
if matched == 0:
child.sendline(passwd)
在 debug.txt 中:
ssh-rsa AAAA..........vcxv233x5v3543sfsfvsv user1@host1
/bin/cat: |: No such file or directory
/bin/cat: ssh: No such file or directory
/bin/cat: user2@host.net: No such file or directory
/bin/cat: cat >> .ssh/authorized_keys: No such file or directory
/bin/cat: >: No such file or directory
/bin/cat: 2>&1: No such file or directory
我看到了两个解决方案:
- 修复 pexpect 命令,将整个字符串识别为一个命令,或者,
- 以假用户身份向标准输入注入/写入密码,但如何!?!?
【问题讨论】:
-
不相关:Python中双引号内的单引号不需要转义:
"_'|'_" -
你考虑过
ssh-copy-id吗? -
@J.F.Sebastian Nope,不可用。
-
ssh-copy-idis just a shell script。如果您安装了 openssh 客户端(ssh命令),那么它应该可用。
标签: linux python-2.7 stdin pexpect