使用python+django+twistd 开发自己的操作和维护系统的一个

使用python+django+twistd 开发自己的操作和维护系统的一个

大家好,又见面了,我是全栈君,今天给大家准备了Idea注册码。

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

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

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

以下上图说明:

使用python+django+twistd 开发自己的操作和维护系统的一个

使用freemind整理了下思路:

使用python+django+twistd 开发自己的操作和维护系统的一个

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

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错误!

passclass Moinitor_client_factory(protocol.ReconnectingClientFactory): def __init__(self, service): #还没想要要写什么 self.service = service protocol = Monitor_Protocolclass Client_Service(service.Service): def __init__(self): pass def startService(self): service.Service.startService(self)#配置文件開始port = 10000host = '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界面截图吧!


使用python+django+twistd 开发自己的操作和维护系统的一个

代码下载

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/117662.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • Deep Learning中的一些Tips详解(RELU+Maxout+Adam+Dropout)「建议收藏」

    Deep Learning中的一些Tips详解(RELU+Maxout+Adam+Dropout)「建议收藏」本文主要讲如果我们的DeepLearning出现了一些不好的结果,我们该怎么去解决。学习前请先参考:反向传播算法(Backpropagation)—-GradientDescent的推导过程。

    2022年4月29日
    59
  • linux云服务器上安装node[通俗易懂]

    linux云服务器上安装node[通俗易懂]云服务器上搭建nodejs前言第一步:下载wget第二步:下载nodejs功能快捷键合理的创建标题,有助于目录的生成如何改变文本的样式插入链接与图片如何插入一段漂亮的代码片生成一个适合你的列表创建一个表格设定内容居中、居左、居右SmartyPants创建一个自定义列表如何创建一个注脚注释也是必不可少的KaTeX数学公式新的甘特图功能,丰富你的文章UML图表FLowchart流程图导出与导入导出导入前言这篇是记录搭建nodejs过程的一篇文章,同时也希望能够帮到跟我一样对linux零基础的同学们。第一

    2025年8月29日
    8
  • pidstat_使用pidstat查看进程资源使用情况

    pidstat_使用pidstat查看进程资源使用情况引言在查看系统资源使用情况时,很多工具为我们提供了从设备角度查看的方法。例如使用iostat查看磁盘io统计信息:linux:~#iostat-d3Device:tpsBlk_read/sBlk_wrtn/sBlk_readBlk_wrtnsda1.670.0040.000…

    2025年5月23日
    4
  • java getclassloader_关于getClass(),Object.class,getClassLoader的理解

    java getclassloader_关于getClass(),Object.class,getClassLoader的理解1、对Class类的理解:Class类包含了类的信息,如构造方法、方法、属性,可用于反射。以下是所有方法2、获取Class类对象的几种方法:Testtest=newTest();(1).test.getClass();在运行时确定,所以运行实例才是该类对象。super.getClass()不能获得父类的类对象,仍然是当前类对象。获得父类类对象:test.getClass().getSup…

    2022年6月11日
    21
  • Java 文件上传与下载

    Java 文件上传与下载MultipartFile这个类一般是用来接受前台传过来的文件Part能获取所有的请求参数的参数名,而Parameter只能获取非文件类型的参数名Part不能获得普通参数的参数值,只能从getParameter(String)获取参数值想要上传文件到服务器,必须使用Part获得二进制的输入流Part能获得上传文件的文件大小、文件类型HttpServletRequestrequest@RequestPart…

    2022年5月14日
    45
  • 黄金t+d基础知识解析

    黄金t+d基础知识解析投资者无论进行哪种投资,如果想要深入市场,就要掌握最基本的专业术语。比如黄金t+d,它是黄金延期交易,是以保证金交易方式进行交易的、通过引入延期补偿机制来平缓供求矛盾的一种交易模式。投资者可以选择合约交易日当天交割,也可以延期交割。领峰作为互联网金融时代最出色的黄金交易平台之一,始终与最新Fintech科技并肩齐行,为客户提供现货黄金、白银等热门产品交易服务。为广大客户提供第一手环球金融资讯及市场点评,从基本面深入到技术面,精选头条动态为投资者指点迷津。黄金t+d基础知识解析首先来了解一下什么是黄.

    2022年5月28日
    31

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号