• Python TCP Socket 传输服务器资源信息(C/S)


    服务器端脚本,接受客户端发送的数据,保存在字典里;

    每五秒触发一下定时器把数据写到/tmp/system_info,追加写到/tmp/月日_ip的历史文件;

    6小时删除30天前的历史文件。 

    #!/usr/bin/env python
    # coding:utf8
    from socket import *
    import os
    import threading
    import time
    import datetime
    HOST=''
    PORT=21567
    BUFSIZ=2048
    ADDR=(HOST,PORT)
    
    tcpSerSock = socket(AF_INET,SOCK_STREAM)
    tcpSerSock.bind(ADDR)
    tcpSerSock.listen(10)
    dic={}
    ip_set=set()
    file_path='/tmp/'
    def load():
        string=''
        for k in dic.keys():
            today=time.strftime('%m%d', time.localtime(time.time()))+'_'+k.split('.')[3]
            if not os.path.exists(file_path+today):
                os.system('touch ' +file_path+today)
            s = k
            for l in dic[k]:
                s += ' '+l
            string+=','.join(s.split()) + '
    '
            string1=time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))+':'+','.join(s.split()) + '
    '
            with open('/tmp/'+today, 'a') as f:
                f.write(string1)
            dic.pop(k)
        with open('/tmp/system_info', 'wt') as f:
            f.write(string)
    timer = threading.Timer(5.0, load)
    timer.start()
    def remove():
        for k in list(ip_set):
            overdue=str(datetime.date.today()+datetime.timedelta(-30))[5:7]+ 
                    str(datetime.date.today() + datetime.timedelta(-30))[8:]+
                    '_' +k.split('.')[3]
            if os.path.exists(file_path+overdue):
                os.remove(file_path+overdue)
        timer2 = threading.Timer(21600.0, remove)
        timer2.start()
    timer = threading.Timer(5.0, load)
    timer.start()
    timer2 = threading.Timer(21600.0, remove)
    timer2.start()
    while True:
        tcpCliSock, addr = tcpSerSock.accept()
        data = tcpCliSock.recv(BUFSIZ)
        tcpCliSock.close()
        dic[addr[0]]=data.split()
        ip_set.add(addr[0])

    客户端脚本,每五秒向服务端发送一次数据:

    *客户端的硬盘数据需要调试

    #!/usr/bin/env python
    # coding:utf8
    from socket import *
    import os
    from time import sleep
    HOST='monitoring_service'
    PORT=21567
    BUFSIZ=2048
    ADDR=(HOST,PORT)
    
    while True:
        tcpCliSock = socket(AF_INET, SOCK_STREAM)
        tcpCliSock.connect(ADDR)              #尝试连接
        while True:
            data = os.popen("free  | head -2 | tail -1 | awk '{print $2,$3}'").read().strip('
    ') +
            ' ' + os.popen("vmstat | tail -1 | awk -F ' ' '{print $15}'").read().strip('
    ') +
            ' ' + os.popen("df | head -2 | tail -1 | awk '{print $6,$2,$3}'").read().strip('
    ')+
            ' ' + os.popen("df |  tail -2 |head -1| awk '{print $6,$2,$3}'").read().strip('
    ')
            tcpCliSock.send(data)               #发送消息
            break
        tcpCliSock.close()                      #关闭客户端连接
        sleep(5)

    服务器端把当前客户端的 IP、总内存、使用内存、CPU空闲率、/分区标示、/分区硬盘容量、/分区已使用容量、数据分区标示、数据分区硬盘容量、数据分区已使用容量以字符串的方式写到文本里。

    例:

    192.168.1.121,15G,3.1G,100
    192.168.1.42,125G,7.3G,100
    192.168.1.43,125G,2.2G,100

    #!/usr/bin/env python

    # coding:utf8

    from socket import *

    import os

    import threading

    import time

    import datetime

    HOST=''

    PORT=21567

    BUFSIZ=2048

    ADDR=(HOST,PORT)

     

    tcpSerSock = socket(AF_INET,SOCK_STREAM)

    tcpSerSock.bind(ADDR)

    tcpSerSock.listen(10)

    dic={}

    ip_set=set()

    file_path='/tmp/'

    def load():

        string=''

        for k in dic.keys():

            today=time.strftime('%m%d', time.localtime(time.time()))+'_'+k.split('.')[3]

            if not os.path.exists(file_path+today):

                os.system('touch ' +file_path+today)

            s = k

            for l in dic[k]:

                s += ' '+l

            string+=','.join(s.split()) + ' '

            string1=time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))+':'+','.join(s.split()) + ' '

            with open('/tmp/'+today, 'a') as f:

                f.write(string1)

            dic.pop(k)

        with open('/tmp/system_info', 'wt') as f:

            f.write(string)

    timer = threading.Timer(5.0, load)

    timer.start()

    def remove():

        for k in list(ip_set):

            overdue=str(datetime.date.today()+datetime.timedelta(-30))[5:7]+

                    str(datetime.date.today() + datetime.timedelta(-30))[8:]+

                    '_' +k.split('.')[3]

            if os.path.exists(file_path+overdue):

                os.remove(file_path+overdue)

        timer2 = threading.Timer(21600.0, remove)

        timer2.start()

    timer = threading.Timer(5.0, load)

    timer.start()

    timer2 = threading.Timer(21600.0, remove)

    timer2.start()

    while True:

        tcpCliSock, addr = tcpSerSock.accept()

        data = tcpCliSock.recv(BUFSIZ)

        tcpCliSock.close()

        dic[addr[0]]=data.split()

        ip_set.add(addr[0])

  • 相关阅读:
    推荐系统(10)—— 进化算法、强化学习
    Throttle Debounce 总结
    文件点击下载
    Mongodb安装及启动正确姿势
    事务的ACID是指什么?
    sqlserver 获取时间字段 每月最后一天 分组(分区)最后一条的记录
    echarts map js或json 地图数据下载
    sqlserver 字段 逗号分隔分组 多行数据
    windows10 中文输入法 增加美式键盘 导致 系统部分语言变成英文
    excel 合并相同内容的单元格 vba
  • 原文地址:https://www.cnblogs.com/wangyufu/p/5885944.html
Copyright © 2020-2023  润新知