如何使用pexpect

时间:2017-09-27 04:58:54

标签: python pexpect

我正在尝试将公钥附加到具有pexpect的远程服务器上的授权密钥文件,但它无法正常工作。似乎没有发生输出到文件的重定向,尽管没有错误。这是我的代码:

print "DEGUG: ===  append to authorized keys  START ==="
print "DEBUG:  sending echo <local public key> >> /root/.ssh/authorized_keys"
print "        local public key: " + local_public_key
child.sendline('echo ' + local_public_key + ' >> /root/.ssh/authorized_keys')
child.expect(prompt)
child.expect(prompt)
child.sendline('echo $?')
child.expect(prompt)
ec = child.before.strip()
print("exit code: >>>>" + str(ec) + "<<<<")
print "DEGUG: ===  append to authorized keys  END ==="

这是输出:

DEGUG: ===  append to authorized keys  START ===
DEBUG:  sending echo <local public key> >> /root/.ssh/authorized_keys
    local public key: ssh-rsa 
AAAAB3NzaC1yc2EAAAABIwAAAQEAy408yT80SP2x9rZkR56j4wsbpqUSYOW1uY8Lf4XfJLinbtcpwyyYGJCuNbA30ve1+Lt/AJ2d1VdSAS4Afu1LKucFmj2lN8dqKWsCUBYXXtkUHILVelRTglMGFLTbLJofXYwUXA60UWWilYvWJ2j4HRjHgxUP7i0fYy4ruy5zpspZ8Svr+PMY9UjA3HSnPhFB2ZHkC+9kzexfVCM7nvKw9LekxY0x/BrD5z6D+652sr8A9EOgBsg9A/soL4JMycdWmTBDe16O5f4Db5Qt7oqn3Hbw7lki1XULIvTzyNhUtoiGiQiCbCh7G1ba+IccvfrIaK+kpmugeoaTC4zldXEGbw==

echo ssh-rsa 
AAAAB3NzaC1yc2EAAAABIwAAAQEAy408yT80SP2x9rZkR56j4wsbpqUSYOW1uY8Lf4XfJLinbtcpwyyYGJCuNbA30ve1+Lt/AJ2d1VdSAS4Afu1LKucFmj2lN8dqKWsCUBYXXtkUHILVelRTglMGFLTbLJofXYwUXA60UWWilYvWJ2j4HRjHgxUP7i0fYy4ruy5zpspZ8Svr+PMY9UjA3HSnPhFB2ZHkC+9kzexfVCM7nvKw9LekxY0x/BrD5z6D+652sr8A9EOgBsg9A/soL4JMycdWmTBDe16O5f4Db5Qt7oqn3Hbw7lki1XULIvTzyNhUtoiGiQiCbCh7G1ba+IccvfrIaK+kpmugeoaTC4zldXEGbw==
 >> /root/.ssh/authorized_keys
R56j4wsbpqUSYOW1uY8Lf4XfJLinbtcpwyyYGJCuNbA30ve1+Lt/AJ2d1VdSAS4Afu1LKucFmj2lN8dqKWsCUBYXXtkUHILVelRTglMGFLTbLJofXYwUXA60UWWilYvWJ2j4HRjHgxUP7i0fYy4ruy5zpspZ8Svr+PMY9UjA3HSnPhFB2ZHkC+9kzexfVCM7nvKw9LekxY0x/BrD5z6D+652sr8A9EOgBsg9A/soL4JMycdWmTBDe16O5f4Db5Qt7oqn3Hbw7lki1XULIvTzyNhUtoiGiQiCbCh7G1ba+IccvfrIaK+kpmugeoaTC4zldXEGbw==
ssh-rsa 
AAAAB3NzaC1yc2EAAAABIwAAAQEAy408yT80SP2x9rZkR56j4wsbpqUSYOW1uY8Lf4XfJLinbtcpwyyYGJCuNbA30ve1+Lt/AJ2d1VdSAS4Afu1LKucFmj2lN8dqKWsCUBYXXtkUHILVelRTglMGFLTbLJofXYwUXA60UWWilYvWJ2j4HRjHgxUP7i0fYy4ruy5zpspZ8Svr+PMY9UjA3HSnPhFB2ZHkC+9kzexfVCM7nvKw9LekxY0x/BrD5z6D+652sr8A9EOgBsg9A/soL4JMycdWmTBDe16O5f4Db5Qt7oqn3Hbw7lki1XULIvTzyNhUtoiGiQiCbCh7G1ba+IccvfrIaK+kpmugeoaTC4zldXEGbw==
[root@slccaa01cn01 ~]#  >> /root/.ssh/authorized_keys
[root@slccaa01cn01 ~]# echo $?
echo $?
0
[root@slccaa01cn01 ~]# exit code: >>>>echo $?
0
[root@slccaa01cn01 ~]<<<<
DEGUG: ===  append to authorized keys  END ===

当我在远程检查authorized_keys文件时,不会添加新密钥。 似乎密钥已回显到stdout而不是写入文件。不确定如何解决此问题。

1 个答案:

答案 0 :(得分:1)

好像您忘记删除\n中的尾随local_public_key字符。所以试试这样:

child.sendline('echo ' + local_public_key.strip() + ' >> /root/.ssh/authorized_keys')
#                                        ^^^^^^^^