代码之家  ›  专栏  ›  技术社区  ›  Lidia

如何使用pexpect附加到远程服务器上的文件

  •  0
  • Lidia  · 技术社区  · 7 年前

    我正试图用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 似乎密钥被回显到标准输出,而不是写入文件。 不确定如何解决此问题。

    1 回复  |  直到 7 年前
        1
  •  1
  •   pynexj    7 年前

    好像你忘了删除尾随 \n local_public_key

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