安装系统后,全自动修改IP,DNS,计算机名,

查看 22|回复 0
作者:zx003   
# 因多媒体室是python环境,所有就不编译了.
# 需要自己拿去改.运行后全自动按照 MAC 对应 PC 网卡修改.
# 撩撩草草的将就用.反正我这是没问题的.
[Python] 纯文本查看 复制代码
import sys
import ctypes
import os
import subprocess
import psutil
from tkinter import messagebox
# 管理员权限检测
def is_admin():
    try:
        return ctypes.windll.shell32.IsUserAnAdmin()
    except:
        return False
# 静态IP配置
def set_static_ip(interface_name, ip_address, subnet_mask, gateway):
    try:
        subprocess.run(
            ['netsh', 'interface', 'ipv4', 'set', 'address',
             f'name={interface_name}', 'source=static',
             f'addr={ip_address}', f'mask={subnet_mask}', f'gateway={gateway}',
            check=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True,
            encoding='gbk'
        )
        messagebox.showinfo('提示'," IP 地址、子网掩码和网关设置成功。")
    except subprocess.CalledProcessError as e:
        messagebox.showwarning('警告', f"设置失败: {e.stderr}")
# DNS配置
def set_dns(interface_name, dns_servers):
    try:
        # 清除现有 DNS 配置
        subprocess.run(
            ['netsh', 'interface', 'ipv4', 'set', 'dns', f'name={interface_name}', 'source=dhcp',
            check=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True,
            encoding='gbk'
        )
        # 添加新的 DNS 服务器
        for i, dns in enumerate(dns_servers):
            cmd = [
                'netsh', 'interface', 'ipv4', 'add', 'dns',
                f'name={interface_name}', f'addr={dns}'
            ]
            if i > 0:
                cmd.append('index=2')  # 第二个 DNS 使用 index=2
            subprocess.run(cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
                           encoding='gbk')
        messagebox.showinfo('提示',"DNS 设置成功。")
    except subprocess.CalledProcessError as e:
        messagebox.showwarning(f"DNS 设置失败: {e.stderr}")
# 计算机名修改
def change_computer_name(new_name):
    """更改 Windows 计算机名。"""
    try:
        # 使用 wmic 命令修改计算机名
        cmd = f'wmic computersystem where name="%computername%" call rename "{new_name}"'
        result = os.system(cmd)
        if result == 0:
            messagebox.showinfo('提示', f" 计算机名已更改为:{new_name}")
        else:
            messagebox.showwarning('警告', "修改失败,请确认是否以管理员身份运行此脚本。")
    except Exception as e:
        messagebox.showwarning(f"出现错误:{e}")
# 获取配置文件
def config_txt():
    config_ip_name = []
    config_dict = {}
    with open("config.txt", "r", encoding="utf-8") as f:
        for index, line in enumerate(f):
            # 获取网关, 掩码, DNS
            if index
配置文件内容:
gateway=网关
mask=掩码
dns=dns1
dns2=dns
200-00-00-00-00-02,192.168.1.2,计算机名2


config.png (34.45 KB, 下载次数: 0)
下载附件
2025-5-27 12:38 上传

地址, 计算机

您需要登录后才可以回帖 登录 | 立即注册

返回顶部