一、OpenWRTPython 的安装与配置
1、安装 OpenWRTPython
opkg update
opkg install python-mini
2、配置 python 环境
export PYTHONPATH=/usr/lib/python2.7:$PYTHONPATH
export PATH=/usr/lib/python2.7:$PATH
3、测试 python 环境
python2.7 -c "import os;print(os.environ)"
二、OpenWRTPython 网络编程基础
1、使用 socket 进行网络编程
import socket
HOST = '127.0.0.1' # 需要监听的主机地址
PORT = 8888 # 监听端口
# 创建一个 socket 对象
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 将 socket 绑定到指定地址、端口上
s.bind((HOST, PORT))
# 开始监听
s.listen(5)
while True:
# 等待客户端连接
conn, addr = s.accept()
print('Connected by', addr)
# 接收客户端发送的数据
data = conn.recv(1024)
if not data:
continue
# 处理数据
print('Received', repr(data))
# 发送数据
conn.sendall(data)
# 关闭连接
conn.close()
2、使用 urllib 进行网络访问
from urllib import request, parse
import json
url = 'https://api.github.com/users'
data = {"name": "jack", "age": 20}
# 创建请求
req = request.Request(url)
req.add_header('Content-Type', 'application/json')
# 发送数据
response = request.urlopen(req, json.dumps(data).encode('utf-8'))
# 处理响应
print(response.status)
print(response.reason)
print(response.read().decode('utf-8'))
三、OpenWRTPython 应用案例
1、路由器管理程序
from flask import Flask
import os
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!
"
@app.route("/reboot")
def reboot():
os.system("reboot")
return "Rebooting...
"
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8888, debug=True)
2、网络监控程序
import urllib.request
import re
import time
def get_speed():
response = urllib.request.urlopen("http://speedtest.net/")
html = response.read().decode()
# 解析页面
rx_speed = re.compile(
r"(?s)[\d\.]+? Mb/s[\s\S]*?"
"[\d\.]+? Mb/s")
match = rx_speed.search(html)
if match:
return {"download": match.group(1), "upload": match.group(2)}
while True:
speed = get_speed()
print("Download: ", speed.get("download", "Unknown"))
print("Upload: ", speed.get("upload", "Unknown"))
time.sleep(10)
四、OpenWRTPython 的开发工具
1、使用 VSCode 进行开发
{
"python.pythonPath": "/usr/bin/python2.7",
"python.autoComplete.extraPaths": [
"/usr/lib/python2.7",
"/usr/lib/python2.7/site-packages"
],
"python.formatting.provider": "autopep8",
"python.formatting.autopep8Args": ["--max-line-length=100"],
"python.linting.enabled": true,
"python.linting.pylintEnabled": false,
"python.linting.flake8Enabled": true,
"python.linting.flake8Args": ["--max-line-length=100"]
}
2、使用 PyCharm 进行开发
# 配置 Python 解释器
Settings -> Project: xxx -> Project Interpreter -> Add -> SSH Interpreter -> 输入主机地址、帐号、密码 -> 配置路径
以上就是 OpenWRTPython 的综合介绍,介绍了它的安装与配置、网络编程基础、应用案例和开发工具。OpenWRTPython 作为一个 Python 环境,在 OpenWRT 路由器上有着广泛的应用,可以方便地进行网络编程和嵌入式设备编程。