这几天在学习python,就参照网上的资料写了个小脚本练练手。
这个脚本也在服务器上测试过,是可以用的,但是如果大家是通过外网网卡登录到各服务器上会比较慢,最好是将脚本放到一台服务器上(监控服务器),然后通过内网网卡进行连接检查,如果都加了host的情况下还是很快的。。。不会耽误太久。。
#!/usr/bin/env python
#ssh_cmd_ver2.py
#coding:utf-8
import pexpect
def ssh_cmd(ip, user, passwd, cmd):
ssh = pexpect.spawn('ssh "%s"' % (user, ip, cmd))
try:
i = ssh.expect(['password: ', 'continue connecting (yes/no)?'])
if i == 0 :
ssh.sendline(passwd)
r = ssh.read()
elif i == 1:
ssh.sendline('yes\n')
ssh.expect('password: ')
ssh.sendline(passwd)
r = ssh.read()
except pexpect.EOF:
ssh.close()
return r
hosts = '''
192.168.1.12:root:1357924680:df -h,uptime
192.168.1.13:root:1357924680:df -h,uptime
'''
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)
阅读(6893) | 评论(0) | 转发(0) |