pexpect
pexpect.py だけ持ち込めば使える pexpect はとても便利. python でごりごりコードが書ける分だけ expect よりも便利! デプロイ、ログ収集と大活躍. 以下、ssh でログインして uname -r の結果だけを拾ってくる例.
from sys import stdout, stderr from getpass import getpass from pexpect import spawn, EOF host = raw_input("server: ") id = raw_input("id: ") pw = getpass("%s's password: " % id) c = spawn('ssh %s@%s' % (id, host)) #c.logfile = stderr i = c.expect_exact(['yes', 'assword: ']) if i == 0: # unknown ssh key c.sendline('yes') c.expect_exact('assword: ') c.sendline(pw) c.expect_exact('$ ') c.sendline('uname -r') c.readline() # skip remote echo stdout.write(c.readline()) c.expect_exact('$ ') c.sendline('exit') c.expect_exact(EOF) c.close()