在Linux服务器管理中,经常需要手动更改网络配置,如设置静态IP地址、更改DNS服务器等。这些操作虽然不复杂,但重复执行时会显得繁琐。Python作为一种强大的脚本语言,可以用来自动化这些任务,提高效率并减少错误。本文将介绍如何使用Python脚本来自动化Linux网络配置。
更改静态IP地址
手动更改静态IP地址通常涉及编辑网络配置文件或使用命令行工具。使用Python脚本,我们可以自动化这一过程,确保每次更改都准确无误。
示例代码
import os
# 定义网络接口名称和新的静态IP地址
interface_name = "ens33"
new_ip_address = "192.168.152.128"
netmask = "255.255.255.0"
gateway = "192.168.152.2"
# 编辑网络配置文件
with open(f"/etc/sysconfig/network-scripts/ifcfg-{interface_name}", "w") as file:
file.write(f"""DEVICE={interface_name}
TYPE=Ethernet
BOOTPROTO=none
ONBOOT=yes
IPADDR={new_ip_address}
NETMASK={netmask}
GATEWAY={gateway}
DNS1=8.8.8.8
DNS2=8.8.4.4
""")
# 重启网络服务使更改生效
os.system(f"sudo systemctl restart network")
设置DNS服务器
更改DNS服务器地址是网络配置中的另一个常见任务。通过Python脚本,我们可以轻松地更新 /etc/resolv.conf
文件。
示例代码
# 定义新的DNS服务器地址
new_dns_servers = ["8.8.8.8", "8.8.4.4"]
# 写入新的DNS服务器地址到resolv.conf文件
with open("/etc/resolv.conf", "w") as file:
file.write(f"""# Generated by Python script
nameserver {new_dns_servers[0]}
nameserver {new_dns_servers[1]}
""")
print("DNS servers have been updated.")
检查网络配置是否成功
更改配置后,我们需要验证新的IP地址和DNS服务器是否已经正确应用。
示例代码
import subprocess
def check_ip_address(interface_name):
result = subprocess.run(["ip", "addr", "show", interface_name], capture_output=True, text=True)
return result.stdout
def check_dns_resolution():
result = subprocess.run(["dig", "google.com"], capture_output=True, text=True)
return result.stdout
# 检查IP地址
ip_address_output = check_ip_address("ens33")
print("IP Address Configuration:")
print(ip_address_output)
# 检查DNS解析
dns_resolution_output = check_dns_resolution()
print("\nDNS Resolution Check:")
print(dns_resolution_output)
通过运行这些Python脚本,你可以快速更改网络配置,并验证更改是否成功。自动化网络配置不仅节省时间,还能减少因手动配置错误导致的问题。