背景
公司有600多台服務器,打算寫一個小程序,能一眼看見哪些服務器不在線。
大體思路是:
1、把所有服務器ip存進數據庫,ping命令判斷服務器是否在線
2、更新數據庫中ip的狀態
3、簡單的web顯示出來
4、優化程序,美觀頁面
一、python檢測IP在線
fping命令,它是對一個文件的批量ping,瞬間完成的,如果ping不通,那就較慢,日常ping不通的畢竟是少數,所以這個非常適用。
這個命令需要安裝,直接yum就行,yum install fping -y
創建fping.sh的shell腳本 #!/bin/bash rm -f result.txt cat ipmi_ping.txt | fping > result.txt
執行結果:
二、讀取mysql數據
1、創建一張數據表,存放ip等信息
#創建一個表 create table ip_table( id int auto_increment, #id自增 ipaddress char(15) not null, #地址禁止為空 application char(24), status char(6), primary key(id) ); #插入部分數據 insert into ip_table values(id,'10.30.0.101','郵箱服務器','在線'); insert into ip_table values(id,'10.1.100.1','核心交換機','在線'); insert into ip_table values(id,'10.1.50.30','開發庫','在線'); insert into ip_table values(id,'10.1.80.115','openstack控制節點','在線'); insert into ip_table values(id,'10.1.80.116','openstack計算節點','在線'); insert into ip_table values(id,'10.1.80.117','openstack塊存儲節點','在線'); commit;
2、python實現讀取數據表中的內容,並寫入到一個本地文件
# -*- coding:utf-8 -*- import pymysql def get_loan_number(file): connect = pymysql.connect( host="10.1.80.200", port=3306, user="alex", passwd="alex", db="ip", charset='utf8' ) print("寫入中,請等待……") cursor = connect.cursor() #獲取游標 sql = "select ipaddress from ip_table" #執行的sql cursor.execute(sql) #執行數據庫操作 number = cursor.fetchall() #查詢並返回所有結果 fp = open(file, "w") loan_count = 0 for loanNumber in number: loan_count += 1 fp.write(loanNumber[0] + "\n") fp.close() cursor.close() #關閉指針對象 connect.close() #關閉數據庫連接 print("寫入完成,共寫入%d條數據……" % loan_count) if __name__ == "__main__": file = r"loanNUmber.txt" get_loan_number(file)
二、執行fping腳本,並將結果輸出到result文件
# -*- coding:utf-8 -*- import pymysql import os def get_loan_number(file): connect = pymysql.connect( host="localhost", port=3306, user="root", passwd="12345678", db="ip", charset='utf8' ) print("寫入中,請等待……") cursor = connect.cursor() #獲取游標 sql = "select ipaddress from ip_table" #執行的sql cursor.execute(sql) #執行數據庫操作 number = cursor.fetchall() #查詢並返回所有結果 fp = open(file, "w") loan_count = 0 for loanNumber in number: loan_count += 1 fp.write(loanNumber[0] + "\n") fp.close() cursor.close() #關閉指針對象 connect.close() #關閉數據庫連接 print("寫入完成,共寫入%d條數據……" % loan_count) f = os.system('sh /ping/fping.sh') if __name__ == "__main__": file = r"ipmi_ping.txt" get_loan_number(file)
三、讀result.txt文件,將IP is unreachable的行提取更新狀態‘不在線’
#!/usr/bin/python3 # -*- coding:utf-8 -*- import pymysql import os def get_loan_number(file): connect = pymysql.connect( host="localhost", port=3306, user="root", passwd="12345678", db="checkip", charset='utf8' ) print("寫入中,請等待……") cursor = connect.cursor() #獲取游標 sql = "select ipaddress from ip_table" #執行的sql cursor.execute(sql) #執行數據庫操作 number = cursor.fetchall() #查詢並返回所有結果 fp = open(file, "w") loan_count = 0 for loanNumber in number: loan_count += 1 fp.write(loanNumber[0] + "\n") fp.close() print("寫入完成,共寫入%d條數據……" % loan_count) f = os.system('sh fping.sh') content = open('result.txt','r') first= content.read().split('\n') for i in range(0,len(first)-1): tmp = first[i] ip = tmp[:tmp.index('is')-1] status = '在線' if 'unreachable' in tmp: status = '離線' cursor.execute('update ip_table set status ="%s" where ipaddress ="%s"'%(status,ip)) connect.commit() content.close() cursor.close() #關閉指針對象 connect.close() #關閉數據庫連接 if __name__ == "__main__": file = r"ipmi_ping.txt" get_loan_number(file)
此時已經可以在數據庫中看見status發送了變化。
四、設置get_loan_number每秒執行
#!/usr/bin/python3 # -*- coding:utf-8 -*- import pymysql import os import time def get_loan_number(file): connect = pymysql.connect( host="localhost", port=3306, user="root", passwd="12345678", db="checkip", charset='utf8' ) cursor = connect.cursor() #獲取游標 sql = "select ipaddress from ip_table" #執行的sql cursor.execute(sql) #執行數據庫操作 number = cursor.fetchall() #查詢並返回所有結果 fp = open(file, "w") loan_count = 0 for loanNumber in number: loan_count += 1 fp.write(loanNumber[0] + "\n") fp.close() f = os.system('sh fping.sh >> checkip.log 2>&1') content = open('result.txt','r') first= content.read().split('\n') #通過指定分隔符對字符串進行切片 for i in range(0,len(first)-1): tmp = first[i] ip = tmp[:tmp.index('is')-1] status = '在線' if 'unreachable' in tmp: status = '離線' cursor.execute('update ip_table set status ="%s" where ipaddress ="%s"'%(status,ip)) connect.commit() content.close() cursor.close() #關閉指針對象 connect.close() #關閉數據庫連接 while True: get_loan_number(r"ipmi_ping.txt") time.sleep(3)
五、設計web提取mysql數據
這里我用了flask框架,因為簡單好用。
首先安裝python第三方模塊:
pip3 install flask pip3 install flask_bootstrap pip3 install pymysql
建立base.html
{% extends "bootstrap/base.html" %} {% block title %}Flask{% endblock %} {% block navbar %} <div class="navbar navbar-inverse" role="navigation"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="/">PMSystem</a> </div> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li><a href="/">主機在線平台</a></li> </ul> </div> </div> </div> {% endblock %} {% block content %} <div class="container"> {% block page_content %}{% endblock %} </div> {% endblock %}
建立index.html
{% extends "base.html" %} {% block title %}主機平台{% endblock %} {% block page_content %} <table class="table table-bordered"> <tr> <th>序號</th> <th>IP地址</th> <th>服務</th> <th>是否在線</th> </tr> {% for i in u %} <tr> <td>{{ i[0] }}</td> <td>{{ i[1] }}</td> <td>{{ i[2] }}</td> <td>{{ i[3] }}</td> </tr> {% endfor %} </table> {% endblock %}
建立app.py
from flask import Flask from flask import render_template from flask_bootstrap import Bootstrap import pymysql app = Flask(__name__) bootstrap = Bootstrap(app) @app.route('/') def index(): conn = pymysql.connect(host='10.1.80.110', user='alex', password='alex', db='checkip', charset='utf8') cur = conn.cursor() sql = "SELECT * FROM ip_table" cur.execute(sql) u = cur.fetchall() conn.close() return render_template('index.html',u=u) if __name__ == '__main__': app.run(host='0.0.0.0',debug=True)
運行一下程序:
初步實現了需求。
六、設置后台執行
nohup /python3/bin/python3.5 -u ping.py >> ping.log nohup /python3/bin/python3.5 -u app.py >> app.log 2>&1 &