1、 安装python的Pexpect模块
wget http://jaist.dl.sourceforge.net/project/pexpect/pexpect/Release%202.3/pexpect-2.3.tar.gz
tar xzf pexpect-2.3.tar.gz
cd pexpect-2.3
python setup.py install
2、 执行脚本
可以登录到机器执行一些简单的命令等。。
#!/usr/bin/env python # -*- coding: utf-8 -*- import pexpect from getpass import getpass passwd = getpass() def ssh_cmd(user,ip, cmd): ssh = pexpect.spawn('ssh %s@%s "%s"' % (user,ip,cmd)) try: i = ssh.expect(['password:', 'continue connecting (yes/no)?'], timeout=5) if i == 0 : ssh.sendline(passwd) elif i == 1: ssh.sendline('yes') ssh.expect('password: ') ssh.sendline(passwd) except pexpect.EOF: print "EOF" except pexpect.TIMEOUT: print "TIMEOUT" else: r = ssh.read() print r ssh.close()
if __name__ == '__main__': file=open("/root/python/filelist",'r') a = file.read() file.close() for host in a.split("\n"): if host: user,ip,cmd = host.split("::") print "-- %s run:%s --" % (ip, cmd) ssh_cmd(user,ip,cmd)
more /root/python/filelist
root::1.1.1.1::ls&&date
root::2.2.2.2::ls&&date
................