1、 安装python的Pexpect模块
yum install pexpect
2、 代码
这里主要是用pexpect执行ssh,查看远程uptime和df -h看硬盘状况。
#ssh_cmd.py
#coding:utf-8
import pexpect
def ssh_cmd(ip, user, passwd, cmd):
ssh = pexpect.spawn('ssh "%s"' % (user, ip, cmd))
r = ''
try:
i = ssh.expect(['password: ', 'continue connecting (yes/no)?'])
if i == 0 :
ssh.sendline(passwd)
elif i == 1:
ssh.sendline('yes')
except pexpect.EOF:
ssh.close()
else:
r = ssh.read()
ssh.expect(pexpect.EOF)
ssh.close()
return r
hosts = '''
192.168.10.20:zhujian:abc123:df -h,uptime
192.168.10.31:zhujian:abc123:df -h,uptime
192.168.10.204:root:xx123:restartjboss
'''
for host in hosts.split("\n"):
if host:
ip, user, passwd, cmds = host.split(":")
for cmd in cmds.split(","):
print "-- %s run:%s --" % (ip, cmd)
print ssh_cmd(ip, user, passwd, cmd)
hosts数组格式是:主机IP:用户名:密码:命令 (多个命令用逗号, 隔开)
阅读(5569) | 评论(0) | 转发(0) |