Python脚本:静态IP和自动DHCP之间切换上网

 本文将介绍一个Python脚本,用于自动化网络配置,包括静态IP拨号上网与自动DHCP之间切换上网。该脚本的主要功能是智能切换上网:

  • 静态IP -> 自动DHCP(取消拨号)
  • 自动DHCP -> 静态ip(自动拨号)

Python代码

import subprocess
import platform

# 定义配置参数
STATIC_IP = "192.168.XX.XX"  # 静态IP地址
SUBNET_MASK = "255.255.255.0"  # 子网掩码
INTERFACE_NAME = "以太网"  # 网络接口名称,需根据实际情况调整
DIALUP_NAME = "宽带连接"  # 拨号连接的名称
USERNAME = "155XXXXXXXX"  # 拨号所需用户名
PASSWORD = "XXXXX"  # 拨号所需密码

def is_static_ip_set():
    """检查当前以太网是否已设置为静态IP"""
    try:
        if platform.system() == "Windows":
            output = subprocess.check_output(f'netsh interface ipv4 show config "{INTERFACE_NAME}"', shell=True)
            output = output.decode('gbk')  # 指定编码为 GBK
            return STATIC_IP in output
        else:
            output = subprocess.check_output(f'ip a show {INTERFACE_NAME}', shell=True).decode('utf-8')
            return STATIC_IP in output
    except subprocess.CalledProcessError as e:
        print(f"Error checking static IP: {e}")
        return False

def set_static_ip():
    """设置静态IP"""
    try:
        if platform.system() == "Windows":
            print("Setting static IP...")
            subprocess.run(f'netsh interface ipv4 set address name="{INTERFACE_NAME}" static {STATIC_IP} {SUBNET_MASK}',
                           shell=True)
        else:
            print("Setting static IP for Linux...")
            subprocess.run(f'sudo ip addr add {STATIC_IP}/{SUBNET_MASK} dev {INTERFACE_NAME}', shell=True)
    except Exception as e:
        print(f"Error setting static IP: {e}")

def set_dhcp():
    """设置为DHCP"""
    try:
        if platform.system() == "Windows":
            # 检查拨号连接是否活动,并断开
            if is_dial_up_connected():
                print("拨号连接仍然活动,正在断开连接...")
                disconnect_result = subprocess.run(f'rasdial "{DIALUP_NAME}" /disconnect', shell=True,
                                                   stdout=subprocess.PIPE, stderr=subprocess.PIPE)

                print("Disconnect Output:", disconnect_result.stdout.decode('gbk', errors='ignore'))
                print("Disconnect Error:", disconnect_result.stderr.decode('gbk', errors='ignore'))

            print("Setting DHCP...")
            subprocess.run(f'netsh interface ipv4 set address name="{INTERFACE_NAME}" source=dhcp', shell=True)
        else:
            # 对于Linux,您可能需要执行不同的命令来断开拨号连接
            if is_dial_up_connected():
                print("拨号连接仍然活动,正在断开连接...")
                disconnect_result = subprocess.run(f'sudo nmcli con down "{DIALUP_NAME}"', shell=True,
                                                   stdout=subprocess.PIPE, stderr=subprocess.PIPE)

                print("Disconnect Output:", disconnect_result.stdout.decode('utf-8', errors='ignore'))
                print("Disconnect Error:", disconnect_result.stderr.decode('utf-8', errors='ignore'))

            print("Setting DHCP for Linux...")
            subprocess.run(f'sudo dhclient {INTERFACE_NAME}', shell=True)
    except Exception as e:
        print(f"Error setting DHCP: {e}")

def is_dial_up_connected():
    """检查拨号连接是否处于活动状态"""
    try:
        if platform.system() == "Windows":
            output = subprocess.check_output('rasdial', shell=True).decode('gbk', errors='ignore')
            return DIALUP_NAME in output
        else:
            # 对于 Linux,您可以根据您正在使用的拨号工具进行检查
            output = subprocess.check_output('nmcli -t -f NAME con show --active', shell=True).decode('utf-8')
            return DIALUP_NAME in output
    except subprocess.CalledProcessError as e:
        print(f"Error checking dial-up connection: {e}")
        return False

def dial_up():
    """拨号上网"""
    try:
        print("Dialing up...")
        result = subprocess.run(
            f'rasdial "{DIALUP_NAME}" {USERNAME} {PASSWORD}',
            shell=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE
        )

        print("Standard Output:", result.stdout.decode('gbk', errors='ignore'))  # 输出拨号结果
        print("Standard Error:", result.stderr.decode('gbk', errors='ignore'))  # 输出错误信息

        if result.returncode != 0:
            print(f"拨号失败,错误代码: {result.returncode}")
            if "错误" in result.stderr.decode('gbk', errors='ignore'):
                print("拨号错误信息:", result.stderr.decode('gbk', errors='ignore'))
    except Exception as e:
        print(f"Error dialing up: {e}")

def main():
    if is_static_ip_set():
        print("当前设置为静态IP,正在切换到DHCP...")
        set_dhcp()
    else:
        print("当前未设置静态IP,正在切换到静态IP...")
        set_static_ip()
        # 拨号上网
        dial_up()

if __name__ == "__main__":
    main()

注意事项:记得使用“pyinstaller --onefile 你的python脚本.py”命令编译成exe文件,还需要设置exe文件的管理员权限启动。

总结:通过这段Python代码,用户可以轻松地在静态IP拨号上网和自动DHCP之间切换上网。这使得网络管理变得更加高效和自动化。希望本篇博客能帮助到你。

若有任何问题,欢迎留言讨论!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值