服務器巡檢shell腳本,python生成excel文檔並郵件發出

背景及思路:

五一小長假之前,公司要求我做一次服務器巡檢。

1、寫了一個簡單的腳本獲取服務器的各種基礎信息:cpu,內存,swap分區使用情況,磁盤,網卡信息種種,具體見腳本,將這些信息追加到一個文件中,然後在監控機上做一次彙總,彙總方式就不詳談,我用的是for循環ssh追加

2、然後利用python的xlsxwriter模塊生成excel

3、最後利用python髮帶附件爲excel的郵件到指定郵箱


獲取服務器信息部分腳本:

#取所需要的內網IP
Int_ip=`ifconfig|awk '/inet addr/ {gsub(/:/," ");print $3}'|egrep "^192.168.18"|head -1`
#取除該內網ip以及127.0.0.1之外的所有ip
Out_ip_list=`ifconfig|awk '/inet addr/ {gsub(/:/," ");print $3}'|grep -v $Int_ip|grep -v 127.0.0.1`
#取內存總值,單位爲G,四捨五入
Memory=`free -m|awk '/Mem/ {printf ("%.f\n",$2/1024)}'`
#取內存fr
ee值,從系統角度看,取的是第一行的free
Memory_free=`free -m|awk '/Mem/ {printf "%.f\n",$4/1024}'`
#取CPU核數
Cpu_num=`grep processor /proc/cpuinfo|wc -l`
#取服務器運行時間
Uptime=`uptime|awk '{print $3}'`
#取最近15分的負載
Load=`uptime|awk '{print $12}'`
#取磁盤大於80%的磁盤目錄
Disk=`df -h|awk '{a=+$(NF-1);if(a>=80)print $NF}'`
#swap分區總值,單位爲G,四捨五入
Swap=`free -m|awk '/Swap/ {printf ("%.f\n",$2/1024)}'`
#swap分區
Swap_free=`free -m|awk '/Swap/ {printf "%.f\n",$4/1024}'`

生成excel
excel.py:
#!/usr/bin/python
# -*- coding: utf-8 -*-
from xlsxwriter import workbook
import ConfigParser
import time
import sendmail
def write_excel(file):
    '''
    1、設置 Excel 樣式
    2、將數據寫入到 Excel 中
    '''
    # 生成 Excel 文件
    work = workbook.Workbook(file)
    # 建立工作表,表名默認
    worksheet = work.add_worksheet()
    # 設置字體加粗、字體大小
    format_title = work.add_format({'bold': True, 'font_size': 16})
    # 設置水平對齊、垂直對齊
    format_title.set_align('center')
    format_title.set_align('vcenter')
    format_body = work.add_format({'font_size': 14})
    # 設置樣式,行高、列寬
    worksheet.set_row(0, 25)
    worksheet.set_column(0, 7, 30)
    worksheet.set_column(8,9,50)
    worksheet.set_column(9,10,100)
    # 定義表頭
    title = (
        '服務器IP',
        '內存大小 GB',
        '內存剩餘 GB',
        'Swap大小 GB',
        'Swap剩餘 GB',
        '運行時間 天',
        '系統負載 ',
        'CPU 核數',
        '磁盤超過80%',
        '其餘IP',
    )
    row = 0
    col = 0
    #寫入表頭
    for item in title:
        item = unicode(item,"utf-8")
        worksheet.write(row, col, item, format_title)
        col+=1
    #寫入數據
    cf = ConfigParser.ConfigParser()
    cf.read('/data/scripts/excel/config_total.txt')
    for ip in cf.sections():
        row+=1
        col = 0
        for opt in cf.options(ip):
            key=cf.get(ip,opt)
            worksheet.write(row,col,key,format_body)
            col+=1
    work.close()
if __name__ == '__main__':
    Excel_name = "Server_%s.xls" %(time.strftime("%Y-%m-%d", time.localtime()))
    write_excel(Excel_name)
    sendmail.send_mail('********@139.com','服務器巡檢表格','fuliao server message',Excel_name)

sendmail.py:

#!/usr/bin/python
import smtplib
from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
import sys
mail_host = 'smtp.163.com'
mail_user = '163郵箱賬號'
mail_pass = '163郵箱密碼'
mail_postfix = '163.com'
def send_mail(to_list,subject,content,name):
    me = mail_user+"<"+mail_user+"@"+mail_postfix+">"
    msg = MIMEMultipart()
    msg['Subject'] = subject
    msg['From'] = me
    msg['to'] = to_list
    msg.attach(MIMEText(content))
    part = MIMEApplication(open(name,'rb').read())
    part.add_header('Content-Disposition','attachment', filename=name)
    msg.attach(part)
    try:
        s = smtplib.SMTP()
        s.connect(mail_host)
        s.login(mail_user,mail_pass)
        s.sendmail(me,to_list,msg.as_string())
        s.close()
        return True
    except Exception,e:
        print str(e)
        return False

最後生成的excel圖:

wKioL1cr8PPRcfyVAAFa5EtDTUg559.png

效果在上面


ps:上傳文件非法,需要腳本的留個郵箱吧,不好意思

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章