memo

思いついたこと、やってみたことをテキトウに残していく。

HEAD / archives / 2011-01 / 2011-01-07.rst

paramiko の使い方

たまに触るとすっかり忘れてたりするから、最低限の使い方をメモっとこうシリーズ。

import os
import sys
import time

import paramiko

username = os.getlogin()
host = 'localhost'
port = 22

# connect to ssh-agent and get keys from agent
agent = paramiko.Agent()
keys = agent.get_keys()

# open RSA private key if exists
rsa_key_path = os.path.expanduser('~/.ssh/id_rsa')
if os.path.exists(rsa_key_path):
    try:
        rsa_key = paramiko.RSAKey(filename=rsa_key_path)
        keys.append(rsa_key)

    except paramiko.PasswordRequiredException:
        import getpass
        password = getpass.getpass('private key password: ')

        rsa_key = paramiko.RSAKey(filename=rsa_key_path, password=password)
        keys.append(rsa_key)

# create SSH transport and connect server
transport = paramiko.Transport((host, port))
transport.connect()

# authentication
for key in keys:
    try:
        # publick key authentication
        transport.auth_publickey(username, key)
        break

    except paramiko.AuthenticationException:
        pass

else:
    import getpass
    password = getpass.getpass('password: ')

    # password authentication
    transport.connect(username=username, password=password)

if not transport.is_authenticated():
    print >> sys.stderr, 'authentication error'
    sys.exit(1)

transport.set_keepalive(60)

while True:
    # create 'session' channel
    channel = transport.open_session()

    # execute command and recv output
    channel.exec_command('uptime')
    while not channel.closed:
        sys.stdout.write(channel.recv(1024))

    time.sleep(5)
powered by blikit