服务器端脚本:
1 #!/usr/bin/env python 2 # coding:utf8 3 from socket import * 4 import os 5 import time 6 HOST=‘‘ 7 PORT=21567 8 BUFSIZ=1024 9 ADDR=(HOST,PORT) 10 11 tcpSerSock = socket(AF_INET,SOCK_STREAM) 12 tcpSerSock.bind(ADDR) #创建套接字 13 tcpSerSock.listen(5) #连接数 14 dic={} 15 while True: 16 tcpCliSock, addr = tcpSerSock.accept() #接受客户端连接 17 data = tcpCliSock.recv(BUFSIZ) #接收客户端数据 18 tcpCliSock.close() #关闭客户端 19 dic[addr[0]]=data.split() 20 os.system(‘touch system_info‘) 21 string=‘‘ 22 for k in dic: 23 s = k + ‘ ‘+ dic[k][0] +‘ ‘+ dic[k][1] +‘ ‘+dic[k][2] 24 string+=‘,‘.join(s.split()) + ‘\n‘ #把字符串中空格转换逗号 25 with open( ‘system_info‘ , ‘w‘) as f: 26 f.write(string)
客户端脚本:
1 #!/usr/bin/env python 2 # coding:utf8 3 from socket import * 4 import os 5 from time import sleep 6 HOST=‘192.168.1.226‘ 7 PORT=21567 8 BUFSIZ=1024 9 ADDR=(HOST,PORT) 10 11 while True: 12 tcpCliSock = socket(AF_INET, SOCK_STREAM) 13 tcpCliSock.connect(ADDR) #尝试连接 14 while True: 15 data = os.popen("free -h | head -2 | tail -1 | awk ‘{print $2,$3}‘").read().strip(‘\n‘) +16 ‘ ‘ + os.popen("vmstat | tail -1 | awk -F ‘ ‘ ‘{print $15}‘").read().strip(‘\n‘) 17 print data 18 tcpCliSock.send(data) #发送消息 19 break 20 tcpCliSock.close() #关闭客户端连接 21 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
时间: 2024-10-14 08:56:47