python初级实战-----主机在线情况监控web
背景
公司有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 &
python初级实战-----主机在线情况监控web的更多相关文章
- python初级实战-----关于邮件发送问题
python发邮件需要掌握两个模块的用法,smtplib和email,这俩模块是python自带的,只需import即可使用.smtplib模块主要负责发送邮件,email模块主要负责构造邮件. sm ...
- 自学Zabbix4.3 zabbix实战监控Web网站性能
自学Zabbix4.3 zabbix实战监控Web网站性能 用zabbix如何监控web性能和可用性呢?一般分为四个步骤:打开网站.登陆.登陆验证.退出,看实例. 1. 检测流程 1. 打开网站:如果 ...
- python 多线程ping大量服务器在线情况
需要ping一个网段所有机器的在线情况,shell脚步运行时间太长,用python写个多线程ping吧,代码如下: #!/usr/bin/python #coding=utf-8 ''' Create ...
- Python接口测试实战5(下) - RESTful、Web Service及Mock Server
如有任何学习问题,可以添加作者微信:lockingfree 课程目录 Python接口测试实战1(上)- 接口测试理论 Python接口测试实战1(下)- 接口测试工具的使用 Python接口测试实战 ...
- Python实现监测抖音在线时间,实时记录一个人全天的在线情况
前言 本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理. 作者:小dull鸟 今天给大家分享一篇有趣的文章,灵感来自于前几天与室友的 ...
- zabbix 监控web网站性能
一直在纠结用什么实例来给大家演示呢?想来想去还是官方的好,那我们怎么用zabbix监控web性能和可用性呢?我们这边分为几个步骤:打开网站.登陆.登陆验证.退出,一共4个小step,看实例. 检测流程 ...
- 优化系统资源ulimit《高性能Linux服务器构建实战:运维监控、性能调优与集群应用》
优化系统资源ulimit<高性能Linux服务器构建实战:运维监控.性能调优与集群应用> 假设有这样一种情况,一台Linux 主机上同时登录了10个用户,在没有限制系统资源的情况下,这10 ...
- zabbix如何监控WEB应用性能
HTTP服务目前最流行的互联网应用之一,如何监控服务的健康状态对系统运维来说至关重要. Zabbix本身提供了对WEB应用程序的监控,比如监控WEB程序的Download Speed,Respon ...
- Spring MVC 程序首页的设置 - 一号门-程序员的工作,程序员的生活(java,python,delphi实战)
body { font-family: "Microsoft YaHei UI","Microsoft YaHei",SimSun,"Segoe UI ...
随机推荐
- Transactional 事务
1.事务场景中,抛出异常被catch后,如果需要回滚,一定要手动回滚 其实像第一种try catch这种把整个包裹起来,这种业务方法也就等于脱离了spring事务的管理,因为没有任何异常会从业务方法中 ...
- VMware for mac inside error solutions
Terminal 下执行 sudo xattr -r -d com.apple.quarantine /Applications/VMware\ Fusion.app 之后就能正常打开镜像安装虚拟机了 ...
- getchar(),scanf(),gets(),cin,输入字符串
#include<iostream>#include<stdio.h>#include<string.h>#include<string>using n ...
- 网络I/O模型总结
把网络IO模型整理了一下,如下图
- ADB interface驱动
原文地址:https://blog.csdn.net/weixin_42108952/article/details/80153402
- numpy知识点
1.nonzero 对于一维数据来说,将返回符合条件的 下标 >>> b1 = np.array([True, False, True, False]) >>> n ...
- Object的数据属性和访问器属性
一.数据属性 1.数据属性:它包含的是一个数据值的位置,在这可以对数据值进行读写. 2.数据属性包含四个特性,分别是: configurable:表示能否通过delete删除属性从而重新定义属性,能否 ...
- 16.Linux-LCD驱动(详解)
在上一节LCD层次分析中,得出写个LCD驱动入口函数,需要以下4步: 1) 分配一个fb_info结构体: framebuffer_alloc(); 2) 设置fb_info 3) 设置硬件相关的操作 ...
- scrapy基础二
应对反爬虫机制 ①.禁止cookie :有的网站会通过用户的cookie信息对用户进行识别和分析,此时可以通过禁用本地cookies信息让对方网站无法识别我们的会话信息 settings.py里开启禁 ...
- 《老梁四大名著情商课》笔记-学学TA,你就是聚会的万人迷
<老梁四大名著情商课>笔记-学学TA,你就是聚会的万人迷 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 现在社会学家有一个统计,说中国处在单身状态大概有2个亿.这些人中 ...