一个简单的Python脚本,用于自动配置CentOS的静态IP地址。你可以将这个脚本保存为.py
文件,然后运行它。
Python
#!/usr/bin/env python3 import os def configure_static_ip(interface, ip_address, netmask, gateway, dns): config_file = f"/etc/sysconfig/network-scripts/ifcfg-{interface}" config_content = f""" TYPE=Ethernet BOOTPROTO=static DEFROUTE=yes IPV4_FAILURE_FATAL=no IPV6INIT=yes IPV6_AUTOCONF=yes IPV6_DEFROUTE=yes IPV6_FAILURE_FATAL=no IPV6_ADDR_GEN_MODE=stable-privacy NAME={interface} DEVICE={interface} ONBOOT=yes IPADDR={ip_address} NETMASK={netmask} GATEWAY={gateway} DNS1={dns} """ with open(config_file, "w") as f: f.write(config_content) os.system("systemctl restart network") if __name__ == "__main__": interface_name = "ens33" ip_address = "192.168.19.137" netmask = "255.255.255.0" gateway = "192.168.19.2" dns_server = "192.168.19.2" configure_static_ip(interface_name, ip_address, netmask, gateway, dns_server) print(f"Static IP configuration for {interface_name} completed successfully!")
请注意以下几点:
- 你需要将
interface_name
、ip_address
、netmask
、gateway
和dns_server
替换为你实际的值。 - 运行脚本时,确保具有足够的权限(使用
sudo
)。 - 脚本将自动创建或更新网卡配置文件,并重启网络服务。