CentOS静态IP配置实战:Python自动化脚本实现

return parts[4]
except subprocess.CalledProcessError:
pass
return None
def backup_config_file(file_path):
backup_path = file_path + ‘.backup’
shutil.copy2(file_path, backup_path)
print(f”原配置文件已备份至: {backup_path}”)
return backup_path
def configure_static_ip(interface, ip_address, netmask_cidr, gateway, dns_servers):
config_dir = ‘/etc/sysconfig/network-scripts’
config_file = os.path.join(config_dir, f’ifcfg-{interface}’)
if not os.path.exists(config_file):
raise FileNotFoundError(f”网络接口配置文件不存在: {config_file}”)
backup_config_file(config_file)
new_lines = []
with open(config_file, ‘r’) as f:
lines = f.readlines
ip_set = False
netmask_set = False
gateway_set = False
dns_set = False
for line in lines:
stripped_line = line.strip
if stripped_line.startswith(‘BOOTPROTO=’):
new_lines.append(‘BOOTPROTO=static
‘)
elif stripped_line.startswith(‘IPADDR=’):
new_lines.append(f’IPADDR={ip_address}
‘)
ip_set = True
elif stripped_line.startswith(‘NETMASK=’) or stripped_line.startswith(‘PREFIX=’):
new_lines.append(f’PREFIX={netmask_cidr}
‘)
netmask_set = True
elif stripped_line.startswith(‘GATEWAY=’):
new_lines.append(f’GATEWAY={gateway}
‘)
gateway_set = True
elif stripped_line.startswith(‘DNS’) and ‘=’ in stripped_line:
continue
elif stripped_line.startswith(‘DEFROUTE=’):
new_lines.append(‘DEFROUTE=yes
‘)
elif stripped_line.startswith(‘ONBOOT=’):
new_lines.append(‘ONBOOT=yes
‘)
else:
new_lines.append(line)
if not ip_set:
new_lines.append(f’IPADDR={ip_address}
‘)
if not netmask_set:
new_lines.append(f’PREFIX={netmask_cidr}
‘)
if not gateway_set:
new_lines.append(f’GATEWAY={gateway}
‘)
if dns_servers:
dns_line = f”DNS1={dns_servers[0]}
new_lines.append(dns_line)
if len(dns_servers) > 1:
new_lines.append(f”DNS2={dns_servers[1]}
)
with open(config_file, ‘w’) as f:
f.writelines(new_lines)
print(f”静态IP配置已成功写入文件: {config_file}”)
def restart_network_service:
try:
print(“正在重启网络服务…”)
subprocess.run([‘systemctl’, ‘restart’, ‘network’], check=True)
print(“网络服务重启成功。”)
except subprocess.CalledProcessError as e:
print(f”警告:重启网络服务失败。错误信息: {e}”)
print(“请手动检查配置文件并重启网络服务。”)
def main:
parser = argparse.ArgumentParser(description=’自动化配置CentOS系统静态IP地址’)
parser.add_argument(‘–ip’, required=True, help=’静态IP地址 (e.g., 192.168.1.100)’)
parser.add_argument(‘–netmask’, type=int, required=True, help=’子网掩码 (CIDR格式, e.g., 24)’)
parser.add_argument(‘–gateway’, required=True, help=’默认网关 (e.g., 192.168.1.1)’)
parser.add_argument(‘–dns’, nargs=’+’, help=’DNS服务器地址 (e.g., 8.8.8.8 8.8.4.4)’, default=[‘8.8.8.8’, ‘8.8.4.4’])
args = parser.parse_args
if not validate_ip(args.ip):
print(“错误:提供的IP地址格式无效。”)
return
if not validate_cidr(args.netmask):
print(“错误:子网掩码必须在0到32之间。”)
return
if not validate_ip(args.gateway):
print(“错误:提供的网关地址格式无效。”)
return
for dns in args.dns:
if not validate_ip(dns):
print(f”错误:提供的DNS地址 ‘{dns}’ 格式无效。”)
return
interface = find_network_interface
if not interface:
print(“错误:无法自动检测到默认的网络接口。”)
return
print(f”检测到网络接口: {interface}”)
print(f”即将配置: IP={args.ip}/{args.netmask}, Gateway={args.gateway}, DNS={args.dns}”)
try:
configure_static_ip(interface, args.ip, args.netmask, args.gateway, args.dns)
restart_network_service
print(”
静态IP配置完成!建议使用 ‘ip addr show {interface}’ 命令验证配置。”)
except Exception as e:
print(f”配置过程中发生错误: {e}”)
if __name__ == ‘__main__’:
main


project_name=python_静态IP配置
filename=requirements.txt
title=项目依赖文件
entrypoint=false
runnable=false
project_final_file=true
# 此脚本使用Python标准库,无额外依赖。

该脚本实现了完整的静态IP配置流程。它首先通过系统命令自动识别当前活跃的网络接口,然后对原配置文件进行安全备份。接着,脚本会重构配置文件内容,将网络启动协议设置为static,并写入用户指定的IP地址、子网掩码、网关和DNS信息。它会尝试重启网络服务以使配置生效。整个过程包含了严格的参数验证和错误处理机制。

CentOS静态IP配置实战:Python自动化脚本实现

脚本使用方法与实战示例

要使用此脚本,您需要将其保存到CentOS服务器上,并赋予执行权限。操作步骤如下:

  1. 将脚本上传至服务器,例如 /usr/local/bin/centos_static_ip.py
  2. 通过命令行授予执行权限:chmod +x /usr/local/bin/centos_static_ip.py
  3. 使用sudo权限执行脚本并传入必要的参数。

实战配置示例:

假设您需要将服务器的IP地址设置为192.168.1.100,子网掩码为24位,网关为192.168.1.1,并使用Google的DNS。

sudo python3 /usr/local/bin/centos_static_ip.py --ip 192.168.1.100 --netmask 24 --gateway 192.168.1.1 --dns 8.8.8.8 8.8.4.4

执行后,脚本将输出详细的执行过程。配置完成后,务必使用ip addr命令验证新的IP地址是否已正确应用。

注意事项与最佳实践

在自动化配置网络的过程中,安全性、稳定性和可恢复性是首要考虑因素。

  • 权限要求:修改系统网络配置需要root权限,因此务必使用sudo来运行脚本。
  • 远程操作风险绝对不要在通过SSH远程连接的服务器上直接运行此脚本,除非您有带外管理(如iDRAC、iLO)等备用访问方式。错误的配置可能导致网络中断,使您失去与服务器的连接。
  • 测试先行:建议先在非生产环境或虚拟机中进行充分的测试,确保脚本行为符合预期。
  • 备份的价值:脚本自动创建的.backup文件是救命的稻草。如果新配置导致网络不可用,您可以手动将备份文件恢复,然后重启网络服务。
  • 接口名称:本脚本设计为自动探测接口。如果您的系统接口名称特殊(如ens192, eth0),请确保脚本能正确识别。

通过遵循这些最佳实践,您可以最大限度地发挥自动化脚本的效能,同时将运维风险控制在最低水平。

内容均以整理官方公开资料,价格可能随活动调整,请以购买页面显示为准,如涉侵权,请联系客服处理。

本文由星速云发布。发布者:星速云。禁止采集与转载行为,违者必究。出处:https://www.67wa.com/134418.html

(0)
上一篇 2025年11月27日 上午1:22
下一篇 2025年11月27日 上午1:23
联系我们
关注微信
关注微信
分享本页
返回顶部