许多开源操作系统和维护系统,例nagios、zabbix、cati等等,但是,当他们得到的时间自己的个性化操作和维护需求,始终无力!

最近的一项研究python。因此,我们认为python+django+twisted要定制一个完全个性化的操作和维护系统。

有几个基本的功能:监控、分析、报警、更甚者直接依据分析的结果进行反应操作。而以上几点通过上述的框架能够比較easy的实现。

以下上图说明:

使用freemind整理了下思路:

以下是一些代码段,完整的代码下载见文档底部:

Server:

#!/usr/bin/env python
#coding:utf-8
__author__ = 'dwj' from twisted.internet.protocol import ServerFactory
from twisted.protocols import basic
import cx_Oracle
from twisted.application import service, internet class Mornitor_Protocol(basic.LineReceiver): def __init__(self):
#
_oracle_conn=cx_Oracle.connect('xxxx', 'xxxx', '192.168.7.17/test', threaded=True)
_oracle_conn.autocommit = True
self.cur = _oracle_conn.cursor()
self._oracle_conn=_oracle_conn def ruku(self, line):
ip=self.transport.getPeer().host
#获取clientIP
line=line.split(':::')
#使用:::切割原始数据
if line[1] in ['cpu', 'mem', 'disk', 'tcp', 'net', 'process_down']:
#依据数据包头来确定使用insert还是update。当是tcp包头的时候插入,其余的更新
if line[1] == 'tcp':
sql = "insert into MORNITOR_BASICINFO (ipadd,time,tcp) values (\'%s\',\'%s\',\'%s\')"%(ip,line[0],line[3])
print sql
self.cur.execute(sql) else:
line_again = line[3].split('::')
sql = 'update MORNITOR_BASICINFO set %s=\'%s\',%s=\'%s\' where ipadd=\'%s\' and time=\'%s\''%(line[1],line_again[0],line[2],line_again[1],ip,line[0])
print sql
self.cur.execute(sql) def connectionMade(self):
print 'Connected!' def lineReceived(self, line):
print line
self.ruku(line)
#接受到数据之后运行入库操作。
def connectionLost(self, reason='connectionDone'):
self._oracle_conn.close()
print 'The db is close... ok!' class Mornitor_Factory(ServerFactory):
#还没想好要初始化什么
def __init__(self,service):
self.service = service protocol = Mornitor_Protocol class Fish_Service(service.Service): def __init__(self):
pass def startService(self):
service.Service.startService(self) #什么都不做,開始服务 # def stopService(self):
# return self._port.stopListening() #配置參数
port = 10000
iface = '127.0.0.1' top_server = service.MultiService() #定义服务容器 fish_server = Fish_Service() #实例化我们的服务
fish_server.setServiceParent(top_server) #把自己定义的服务增加到服务容器 factory = Mornitor_Factory(Fish_Service) #工厂化服务 tcp_server = internet.TCPServer(port, factory, interface=iface) #定义tcp服务
tcp_server.setServiceParent(top_server) #把tcp服务增加到服务容器 application = service.Application('Fish_Service') #给应用起个名字
top_server.setServiceParent(application) #把服务容器丢到应用中去

Client端

from twisted.protocols import basic
from twisted.internet import protocol, defer, task
import Get_basic_info_2 as Huoqu
import guardian as shouhu
import time
from twisted.application import service, internet class Monitor_Protocol(basic.LineReceiver):
#自定义客户端和服务端的连接协议。从basic的line继承 def __init__(self):
#
pass @staticmethod
def huoqu_shuju():
#定义一个函数获取本机的一些状态
now = str(time.strftime('%Y-%m-%d %H:%M:%S')) def add_tag(source, tag1, tag2 = 'none'):
#定义格式化字符串函数
return ':::'.join([now, tag1, tag2, source])
#使用:::分隔时间、简单信息、具体信息、原始信息 tcp = add_tag(Huoqu.net_tcp(), 'tcp')
cpu = add_tag(Huoqu.cpu(), 'cpu', 'cpu_detail')
mem = add_tag(Huoqu.mem(), 'mem', 'mem_detail')
disk = add_tag(Huoqu.disk_usage(), 'disk', 'disk_detail')
net = add_tag(Huoqu.net_rate(), 'net', 'net_detail')
process = add_tag(shouhu.check_alive(), 'process_down', 'process_alived')
result = (tcp, cpu, mem, disk, net, process, )
d = defer.Deferred()
#使用defered返回结果
d.callback(result)
return d def xunhuan(self, list):
#定义循环发送函数
for i in list:
self.sendLine(i) def fasong(self):
#定义程序执行顺序,取得信息后用callback交给发送函数发送
self.huoqu_shuju().addCallback(self.xunhuan) def loop(self):
#使用twist内置的循环函数定义几秒监控数据传送到服务端
l = task.LoopingCall(self.fasong)
l.start(1) def connectionMade(self):
#覆盖协议的connectmade函数。定义于服务端的连接建立后開始循环
print 'Connected!......ok!'
self.loop() def lineReceived(self, line):
#必须覆盖接受函数,否则twist会报not importent错误! pass class Moinitor_client_factory(protocol.ReconnectingClientFactory): def __init__(self, service):
#还没想要要写什么
self.service = service
protocol = Monitor_Protocol class Client_Service(service.Service): def __init__(self):
pass def startService(self):
service.Service.startService(self) #配置文件開始
port = 10000
host = '127.0.0.1' #守护进程
top_service = service.MultiService() #定义服务容器 client_service = Client_Service() #实例化服务类
client_service.setServiceParent(top_service) #把自定义的服务丢到服务容器中 factory = Moinitor_client_factory(client_service) #定义服务工厂化 tcp_service = internet.TCPClient(host, port, factory) #定义tcp连接的服务
tcp_service.setServiceParent(top_service) #把tcp服务丢到服务容器中去 application = service.Application('Fish_Service') #定义应用名字
top_service.setServiceParent(application) #把服务容器丢到应用中去

一些自己定义监控程序是否存活的脚本:

program = {'nginx': ['/opt/nginx/logs/nginx.pid', '/opt/nginx/sbin/nginx'],
'rsync-C': ['/var/run/rsyncd.pid', 'rsync --daemon'],
} def main():
for k in program:
a = get_pid(k, program[k][0])
if isinstance(a, tuple):
print '%s is not running!' % k
print 'Start the program by Horland_guardian!'
subprocess.call(program[k][1], shell=True)
else:
print 'The %s is running!' % k def check_alive():
l_lived = []
l_downed = []
for k in program:
a = get_pid(k, program[k][0])
if isinstance(a, tuple):
l_downed.append(k)
else:
l_lived.append(k)
process_alived = ' '.join(l_lived)
process_down = ' '.join(l_downed) return '::'.join([process_down, process_alived])

django的使用眼下仅仅须要使用到admin模块就能够。

以下是一些代码段:

model

class BasicInfo(models.Model):
ipadd = models.IPAddressField(verbose_name = u'IP地址')
time = models.CharField(max_length=50, verbose_name = u'时间')
cpu = models.CharField(max_length=255, blank=True, verbose_name = u'CPU%')
cpu_detail = models.CharField(max_length=255, blank=True, verbose_name = u'CPU详情')
mem = models.CharField(max_length=255, blank=True, verbose_name = u'内存%')
mem_detail = models.CharField(max_length=255, blank=True, verbose_name = u'内存详情')
disk = models.CharField(max_length=255, blank=True, verbose_name = u'磁盘%')
disk_detail = models.CharField(max_length=255, blank=True, verbose_name = u'磁盘详情')
net = models.CharField(max_length=255, blank=True, verbose_name = u'流量 bytes/s')
net_detail = models.CharField(max_length=1000, blank=True, verbose_name = u'流量详情')
tcp = models.CharField(max_length=255, blank=True, verbose_name = u'tcp连接状态')
process_down = models.CharField(max_length=255, blank=True, verbose_name = u'DOWN-进程')
process_alived = models.CharField(max_length=255, blank=True, verbose_name = u'Process_UP') def Process_DOWN(self):
return '<span style="color: #%s;">%s</span>' % ('ff0000', self.process_down) #拓机的进程用红色标识
Process_DOWN.allow_tags = True

注冊到admin

class BasicInfo_admin(admin.ModelAdmin):

    list_display = ('time', 'cpu', 'cpu_detail', 'mem', 'mem_detail', 'disk', 'disk_detail', 'net', 'net_detail', 'tcp', 'Process_DOWN', 'process_alived')
list_filter = ('ipadd', )
admin.site.register(BasicInfo, BasicInfo_admin)

freemind整理的思路中另一些功能没有实现。眼下这个仅仅能算个简单的demon吧,可是基本实现了监控的目的。欢迎大家给我留言!

以下上个django的admin界面截图吧!

代码下载

http://download.csdn.net/detail/qcpm1983/7611579

版权声明:本文博客原创文章。博客,未经同意,不得转载。

使用python+django+twistd 开发自己的操作和维护系统的一个的更多相关文章

  1. [python] python django web 开发 —— 15分钟送到会用(只能送你到这了)

    1.安装python环境 1.1 安装python包管理器: wget https://bootstrap.pypa.io/get-pip.py sudo python get-pip.py   1. ...

  2. 教你如何将 Sublime 3 打造成 Python/Django IDE开发利器

    Sublime Text 是一款非常强大的文本编辑器, 下面我们介绍如何将 Sublime Text 3 打造成一款 Python/Django 开发利器: 1. 安装 Sublime Text 3 ...

  3. Sublime 3 打造成 Python/Django IDE开发利器

    Sublime Text 是一款非常强大的文本编辑器, 下面我们介绍如何将 Sublime Text 3 打造成一款 Python/Django 开发利器:   1. 安装 Sublime Text ...

  4. Python+Django+SAE系列教程17-----authauth (认证与授权)系统1

    通过session,我们能够在多次浏览器请求中保持数据,接下来的部分就是用session来处理用户登录了. 当然,不能仅凭用户的一面之词,我们就相信,所以我们须要认证. 当然了,Django 也提供了 ...

  5. 在Windows下配置Python+Django+Eclipse开发环境

    一.配置开发环境我的开发环境是:Python2.6.7 + Django1.6.2 + Eclipse1.安装Python2.安装Eclipse的Python插件PyDev如上两步如何操作请点击此进行 ...

  6. Centos 下,配置 Apache + Python + Django + postgresSQL 开发环境

    用 Python 搭建一个 Web 服务器 文章结构 一.安装  Apache.Python.django 二.安装 mod_wsgi,Apache 为 Python 提供的 wsgi 模块  三.将 ...

  7. python——Django(ORM连表操作)

    千呼万唤始出来~~~当当当,终于系统讲了django的ORM操作啦!!!这里记录的是django操作数据库表一对多.多对多的表创建及操作.对于操作,我们只记录连表相关的内容,介绍增加数据和查找数据,因 ...

  8. windows下python+Django+eclipse开发环境的配置

    1.JDK环境的安装 在http://www.java.com/zh_CN/download/faq/develop.xml 页面下,点击JDK下载,下载所需的jdk版本.直接点击安装即可. 2.py ...

  9. python全栈开发day62-两表操作增删改查,外键,if else模板语法

    一.今日内容总结: day62 内容回顾: 1. django有关所有命令: pip install django==1.11.14 django-admin startproject 项目名称 cd ...

随机推荐

  1. 最短路径算法-Dijkstra算法的应用之单词转换(词梯问题)(转)

    一,问题描述 在英文单词表中,有一些单词非常相似,它们可以通过只变换一个字符而得到另一个单词.比如:hive-->five:wine-->line:line-->nine:nine- ...

  2. wwwtyro/cellophane

    wwwtyro/cellophane A dead simple web terminal that gets all of the boilerplate out of the way and le ...

  3. GIS Tools for Hadoop 详细介绍

    2013年Esri美国在开发者大会上演示了GIS数据结合Hadoop分析的一个示例,这个示例赢得了听众的阵阵掌声,我们也许对GIS不是很陌生,但是对Hadoop却不是很清楚,其实Esri是用Java开 ...

  4. vs2008+opencv2.4.9 +win7X64位系统 2.

    小编用自身血淋淋的例子,来给大家做个参考,共耗时近2天时间,终于屈服于安装vs2010,然后配置成功了.但是在这个配置成功后,我终于发现了我08配置不成功的原因,写下心得,供各位参考 1.准备工具 v ...

  5. 安装IntelliJ IDEA JetGroovy(转)

    JetGroovy是一个免费而且开源的专用于支持Groovy和Grails的IntelliJ IDEA插件.这个插件是由JetBrains公司自己开发的,对于Groovy语言和Web框架都提供了无以伦 ...

  6. Android自己定义控件实战——仿淘宝商品浏览界面

    转载请声明出处http://blog.csdn.net/zhongkejingwang/article/details/38656929 用手机淘宝浏览商品详情时,商品图片是放在后面的,在第一个Scr ...

  7. android一些面试题目

    1.ListView怎么提高滑动效率 2.说下你做过项目的包的构架,(联网,解析,activity,database) 重点 3.载入大量图片怎么做(包含小图和查看大图) 怎么降低一次跟server的 ...

  8. .NET/C# RabbitMQ

    本系列文章均来自官网原文,属于个人翻译,如有雷同,权当个人归档,忽喷. RabitMQ 是一个消息中间件,其实就是从消息生产者那里接受消息,然后发送给消息消费者.在这个传输过程中,可以定义一些缓存,持 ...

  9. crontab,想说爱你不easy

    悲剧的背景 跑自己主动化脚本的机器连不上toastserver了, 仅仅能自己写个脚本每天跑了. 当然要放在crontab里了. 5 3 * * * sh ~/nosecron.sh 更悲剧的结果 第 ...

  10. 算法战斗:给定一个号码与通配符问号W,问号代表一个随机数字。 给定的整数,得到X,和W它具有相同的长度。 问:多少整数协议W的形式和的比率X大?

    如果说: 给定一个号码与通配符问号W,问号代表一个随机数字. 给定的整数,得到X,和W它具有相同的长度. 问:多少整数协议W的形式和的比率X大? 进格公式 数据的多组,两排各数据的,W,第二行是X.它 ...