简介
本文介绍了使用pexpect模块实现快速ssh登录的功能
实现
下面的例子,在Python 2.6.5的开发环境和Ubuntu系统下,实现ssh的快速连接的代码实现:
#! /usr/bin/env python
import pexpect
import sys
ip = "ssh root@192.168." + sys.argv[1]
try:
child = pexpect.spawn(ip)
res = child.expect(['Are you sure you want to continue connecting (yes/no)?', 'password:'])
if res == 0:
child.sendline('yes')
child.expect('password:')
child.sendline('liuqi80')
print child.before
child.interact()
except pexpect.EOF, pexpect.TIMEOUT:
print "ssh 192.168." + sys.argv[1] + " timeout"
注1: spawn是Pexpect模块主要的类,用以实现启动子程序,它有丰富的方法与子程序交互从而实现用户对子程序的控制。查看spawn的帮助手册
| __init__(self, c