1. 程式人生 > >python監控服務器

python監控服務器

map cep auto 測試 line nes blog cnblogs rst

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 = [‘[email protected]‘]
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()
結果:

技術分享

測試的時候一堆。修改一下可以用了!!!!

python監控服務器