配合开发测试物联网多路网卡,需要访问路由器接口获取信号量等网络状态信息,然后写入到日志文件上传到云端,由于路由器接口是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)参考:Socket Programming in Python (Guide)Python Socket Programming - Server, Client Example
本文介绍了如何使用Python编程语言访问路由器接口获取网络状态信息,并将其写入日志文件上传到云端。