Ubuntu Python网络设置主要涉及系统网络配置和Python网络编程环境配置,具体如下:
ip a 或 ifconfig(需安装net-tools)。sudo nano /etc/netplan/01-netcfg.yaml # 静态IP示例
network:
version: 2
renderer: networkd
ethernets:
eth0: # 替换为实际网卡名
dhcp4: no
addresses: [192.168.1.100/24] # IP/子网掩码
gateway4: 192.168.1.1
nameservers:
addresses: [8.8.8.8, 8.8.4.4] # DNS
保存后执行:sudo netplan apply。/etc/network/interfaces文件)。sudo nano /etc/environment
添加:http_proxy=http://proxy_ip:porthttps_proxy=http://proxy_ip:portsudo apt update
sudo apt install python3 python3-pip # 安装Python和pip
pip3 install requests aiohttp # 安装高级网络库(如需异步用aiohttp)
HTTP请求(使用requests库):
import requests
proxies = {"http": "http://proxy_ip:port", "https": "http://proxy_ip:port"} # 代理配置(可选)
response = requests.get("http://example.com", proxies=proxies)
print(response.text)
Socket编程(基础网络通信):
import socket
# 服务端
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(("0.0.0.0", 8080)) # 监听所有IP的8080端口
s.listen(1)
conn, addr = s.accept()
print(f"Connected by {addr}")
conn.sendall(b"Hello from server!")
sudo运行Python脚本,可通过chmod +x赋予脚本可执行权限,或通过visudo配置sudoers文件授权特定命令。tcpdump或Wireshark抓包分析网络流量:sudo apt install tcpdump。curl测试网络连通性:curl -I http://example.com。参考资料: