python监控服务器

import paramiko
import threading
import re
import time
import string
from sendmail import send_mail
def ssh2(ip,username,passwd,cmd):

try:

ssh = paramiko.SSHClient()

ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

ssh.connect(ip,2222,username,passwd,timeout=5)

for m in cmd:

stdin, stdout, stderr = ssh.exec_command(m)

# stdin.write("Y") #简单交互,输入 ‘Y’

out = stdout.readlines()

#屏幕输出

for o in out:
# time.sleep(10)
# print(o),
# p = re.compile(r'\d+%')
zf = re.findall(r'(.+%)',o)
# print(re.findall(r'(.+%)',o))
# print("".join(zf))
qc = re.findall(r'\d+',"".join(zf))
# print(qc[-1:])
# print(len(qc[-1:]))
number = map(int,qc[-1:])
for x in number:
# print(type(x))
print(x)
if x > 30:
mailto_list = ['2220781951@qq.com']
send_mail(mailto_list, ip, "ip'disk:%d" % x)
# print(type(numbers))
# a = qc[-3:]
# b = re.findall(r'\d',a)
# c = "".join(b)
# print(len(c))
# print(type(c))

# zhzf = p.findall(o)
# print(zhzf.group())
# zf = ','.join(zhzf)
# print(zf)
# zfint = zf.strip().lstrip().rstrip('%')
# print(zfint)
# print(type(zfint))
# shuzf = int(zfint)
# print(type(shuzf))
# p = re.compile(r'(\d+)%')
# print(p.findall(o))
# print(type(w))
# newint = int(w[0].strip("%")) / 100
# print(newint)


print('%s\tOK\n'%(ip))

ssh.close()

except :

print('%s\tError\n'%(ip))





if __name__=='__main__':
cmd = ['df -h']#你要执行的命令列表
username = "root" #用户名
passwd = "123456" #密码
threads = [] #多线程
print("Begin......")
for i in (50,55,56,128,152):
ip = '192.168.6.'+str(i)
a=threading.Thread(target=ssh2,args=(ip,username,passwd,cmd))
a.start()
for i in (95,):
ip = '192.168.1.'+str(i)
a=threading.Thread(target=ssh2,args=(ip,username,passwd,cmd))
a.start()
结果:

 

测试的时候一堆。修改一下可以用了!!!!

posted on 2017-09-12 12:36  Jt00  阅读(322)  评论(0编辑  收藏  举报

导航