在Linux中,Python命令本身并不能直接進行網絡配置,但你可以使用Python的庫(如os、sys、socket、requests等)來執行網絡相關的操作和配置
import socket
def get_network_interfaces():
interfaces = socket.getaddrinfo(socket.gethostname(), None)
for interface in interfaces:
print(interface[4][0])
get_network_interfaces()
import os
import sys
def set_ip_address(interface, ip_address, subnet_mask):
try:
with open(f"/etc/sysconfig/network-scripts/ifcfg-{interface}", "w") as file:
file.write(f"DEVICE={interface}\n")
file.write(f"BOOTPROTO=static\n")
file.write(f"ONBOOT=yes\n")
file.write(f"IPADDR={ip_address}\n")
file.write(f"NETMASK={subnet_mask}\n")
file.write(f"GATEWAY={get_default_gateway()}\n")
file.write(f"DNS1=8.8.8.8\n")
file.write(f"DNS2=8.8.4.4\n")
except Exception as e:
print(f"Error: {e}")
sys.exit(1)
def get_default_gateway():
try:
with open("/etc/sysconfig/network", "r") as file:
for line in file:
if "GATEWAY=" in line:
return line.split("=")[1].strip()
except Exception as e:
print(f"Error: {e}")
sys.exit(1)
interface = "eth0"
ip_address = "192.168.1.10"
subnet_mask = "255.255.255.0"
set_ip_address(interface, ip_address, subnet_mask)
import os
import sys
def restart_network_service():
try:
os.system("sudo systemctl restart network")
except Exception as e:
print(f"Error: {e}")
sys.exit(1)
restart_network_service()
import requests
url = "https://api.example.com/data"
headers = {"Authorization": "Bearer your_api_key"}
response = requests.get(url, headers=headers)
if response.status_code == 200:
print(response.json())
else:
print(f"Error: {response.status_code}")
請注意,這些示例可能需要根據你的Linux發行版和網絡配置進行調整。在執行這些操作時,請確保你具有適當的權限,并在需要時進行錯誤處理。