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])

原文地址:https://www.cnblogs.com/wangyufu/p/5885944.html