1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Python+pexpectでssh-copy-idを連続実行する

Posted at

pexpectはいつも使い方を忘れてしまうので、メモすることにした。

以下は、対象のホストに対して、連続でsshkeyをコピーするサンプルです。

主な動作は、

  • password:が表示されたら、事前に入力したパスワードをspawnする
  • Are you sure you want to continue connecting (yes/no)? が表示されたら、自動的にyesをspawnする
    の二つ。

コード全体

copy-id.py

import pexpect
import sys
import getpass

ssh_newkey = "Are you sure you want to continue connecting"

def login(child, passwd):

    while True:

        ret = child.expect( [ssh_newkey, "password:", pexpect.EOF, pexpect.TIMEOUT] )

        if ret == 0:
            child.sendline("yes")
            child.readline(),

        if ret == 1:
            child.sendline(passwd)
            child.readline(),
            break

        if ret == 2:
            print "**** fail"
            print child.before
            break

        if ret == 3:
            print "**** Timeout"
            print "**** ret code: %s" % ret
            break

def start(host, passwd):

    cmd = pexpect.spawn("ssh-copy-id %s" % host, timeout=3)
    login(cmd, passwd)


if __name__ == "__main__":

    for host in sys.argv[1:]:
        print host

    passwd = getpass.getpass()

    for host in sys.argv[1:]:
        print "--- START : %s ---" % host
        start(host, passwd)
        print "--- END ---"
        print
    pass
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?