python 簡單監控內存/硬盤空間/以及oracle表空間使用情況
阿新 • • 發佈:2018-05-08
paramico ssh 檢查系統情況由於使用的是內網環境,所以使用用戶名密碼驗證,建議使用密鑰認證
check.py
check.py
import paramiko #獲取ssh連接並執行shellcomand返回正確的結果 def doshell(hostname,port,username,password,shellcommand): ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(hostname,port,username,password) stdin, stdout, stderr = ssh.exec_command(shellcommand) result=stdout.readlines() ssh.close() return result #查詢內存情況 def check_mem(hostname,port,username,password): shellcommand = ‘free -m‘ result=doshell(hostname,port,username,password,shellcommand) line_number=0 for line in result: rs = line.split() if line_number == 0: print(‘[主機地址]%s‘ % hostname) print("[內存]") elif line_number == 2: print(‘程序使用:%s%s ‘ % (rs[2], ‘M‘)) print(‘系統挪用:%s%s ‘ % (rs[3], ‘M‘)) print("[swap]") else: print(‘總大小:%s%s ‘ % (rs[1], ‘M‘)) print(‘空閑內存:%s%s ‘ % (rs[3], ‘M‘)) line_number += 1 #檢查硬盤情況 def check_disk(hostname,port,username,password,part): shellcommand = ‘df -h ‘+part result = doshell(hostname, port, username, password, shellcommand) line_number = 0 for line in result: rs = line.split() if line_number == 0: #print(‘[主機地址]%s‘ % hostname) print("[硬盤]") else : print(‘分區:%s ‘ % (rs[0])) print(‘總大小:%s ‘ % (rs[1])) print(‘空閑空間:%s ‘ % (rs[3])) line_number += 1 #檢查表空間 def check_tablespace(hostname,port,username,password,sid): shellcommand = "export ORACLE_HOME=/whmms/oracle/db11g/;export PATH=$ORACLE_HOME/bin:$PATH;export ORACLE_SID=MSPROD; sqlplus wuyang/wy123456@%s/%s </tmp/tablespace.sql"%(hostname,sid) result=doshell(hostname,port,username,password,shellcommand) print(‘[表空間]‘) for line in result: finded=line.find(‘DATA_TBS‘) if finded != -1: rs = line.split() print(‘表空間名稱:%sG‘ % (rs[0])) print(‘總大小:%sG‘ % (rs[1])) print(‘已使用:%sG‘ % (rs[2])) print(‘空閑:%sG‘ % (rs[3])) print(‘使用率:%sG‘ % (rs[4]))
新建一個文件調用寫好的方法,每次執行main.py腳本會將檢查結果記錄在log.txt中 如何不存在log.txt 會報錯,由於是簡單檢測所以沒有寫自動生成log.txt的代碼 如果需要檢測大量機器建議使用多線程
main.py import check import sys import time #主機列表 hosts=[‘172.16.1.20‘,‘172.16.1.21‘] #端口號 port = 22 #用戶名 username = ‘rzfb‘ #密碼 password = ‘password‘ #需要檢查的分區 part = ‘/dev/mapper/VolData-lvdata‘ #oracle_sid sid = "MSPROD" #將print輸出保存到文件中 output=sys.stdout outputfile=open("log.txt","a") sys.stdout=outputfile type = sys.getfilesystemencoding() #記錄執行時間 print(time.strftime(‘%Y-%m-%d %H:%M:%S‘, time.localtime(time.time()))) #逐個主機檢查運行情況 for hostname in hosts: if hostname == ‘172.16.1.21‘: #兩個數據庫的sid不同所以在這裏做了個判斷 sid="WHMTST" check.check_mem(hostname,port,username,password) check.check_disk(hostname,port,username,password,part) check.check_tablespace(hostname,port,username,password,sid) print("\n\n")
python 簡單監控內存/硬盤空間/以及oracle表空間使用情況