0

Python调用socket模块获取路由器接口数据

 6 months ago
source link: https://chegva.com/5955.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Python调用socket模块获取路由器接口数据

配合开发测试物联网多路网卡,需要访问路由器接口获取信号量等网络状态信息,然后写入到日志文件上传到云端,由于路由器接口是tcp格式,需要使用socket访问。

import socket
import json
import time
import datetime

host = '192.168.1.1'
port = 8888

# 构建要发送的参数
reqid = int(time.time() * 1000)
message = { "action": "get_wwans_status", "reqid": str(reqid) }

def send_tcp_request(host, port, message):
    # 创建一个TCP套接字
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    
    try:
        # 连接到指定的主机和端口
        sock.connect((host, port))
        
        # 发送数据
        message = json.dumps(message)
        sock.sendall(message.encode('utf-8'))
        
        # 接收响应数据
        response = sock.recv(1024)
        
        # 处理响应数据
#       print('Response:', response.decode('utf-8'))
        json_data = json.loads(response.decode('utf-8'))
        return json_data.get("data", [])
        
    finally:
        # 关闭套接字连接
        sock.close()

while True:
    try:
        # 发送TCP请求
        data_array = send_tcp_request(host, port, message)

        current_date = datetime.datetime.now().strftime('%Y%m%d')
        file_name = '/data/log/filebeat_upload/router_' + current_date +'.log'
        with open(file_name, 'a') as output_file:
            for data_object in data_array:
                timestamp = datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z'
                data_object["@timestamp"] = timestamp
                data_object["ttl"] = 0

                data_object["log_type"] = 'chegva_router_monitor'
                output_file.write(json.dumps(data_object) + '\n')
    except Exception as e:
        continue
    # 等待1秒
    time.sleep(1)
Python
安志合个人博客,版权所有 丨 如未注明,均为原创 丨 转载请注明转自:https://chegva.com/5955.html | ☆★★每天进步一点点,加油!★★☆ | 

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK