使用脚本修改hosts文件(bat+python)

使用脚本修改hosts文件(bat+python)

一、使用bat脚本方式

  使用bat修改hosts文件,首先判断默认路径是否存在,如不存在,手工输入目标文件地址(一般用不着):

SET hosts=C:\Windows\System32\drivers\etc\hosts

if exist %hosts% goto hosts
goto nofile

:hosts
@xcopy %hosts% %hosts%_bak\ /d /c /i /y
@ECHO hosts文件已备份,备份目录为%hosts%_bak
@ECHO 1.1.1.1 a.b.c >>%hosts%
@ECHO 2.2.2.2 d.e.f >>%hosts%
ECHO hosts文件已修改,请按任意键退出
@pause > nul
@exit

:nofile
set /p a= 请输入hosts地址(例如:C:\Windows\System32\drivers\etc):
@xcopy %a%\hosts %a%\hosts_bak\ /d /c /i /y
@ECHO HOSTS文件已备份,hosts文件已备份,备份目录为%a%\hosts_bak
@ECHO 1.1.1.1 a.b.c >>%a%\hosts
@ECHO 2.2.2.2 d.e.f >>%a%\hosts
ECHO hosts文件已修改,请按任意键退出
@pause > nul
@exit

为了保证脚本能正常执行,在脚本开头加入管理人权限配置:
(参考脚本之家:https://www.jb51.net/article/193692.htm)

PUSHD %~DP0 & cd /d "%~dp0"
%1 %2
mshta vbscript:createobject("shell.application").shellexecute("%~s0","goto :runas","","runas",1)(window.close)&goto :eof

:runas

执行效果:
在这里插入图片描述

二、使用python

  上述bat脚本使用还是存在缺陷,例如,当需要新增一个IP地址的时候,直接新增行,执行脚本,会导致原来数据重复的问题。(当然bat脚本也实现遍历数据再执行插入操作,但是简单思考之后,使用python更加方便)。
  使用python编写的思路很简单,将所有需要新增的内容写在配置文件hosts_config中,遍历配置文件的数据,执行插入操作,
(一)配置信息如下:
在这里插入图片描述
(二)代码如下:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import shutil
import subprocess

# 系统hosts路径
hosts = r'C:\Windows\System32\drivers\etc\hosts'
hosts_bak = r'C:\Windows\System32\drivers\etc\hosts_bak'
web = ['webmanager.likfspace.com', 'www.likfspace.com']


# 将需要新增的host写到列表中
def read_host_config():
    line = []
    with open('hosts_config') as readhost:
        lines = readhost.readlines()
        for i in lines:
            l = i.replace("\n", "")
            line.append(l)
        return line


# 将系统hosts数据写到列表中
def read_syshosts():
    myhosts = []
    with open(hosts, 'r') as f:
        myhost = f.readlines()
        for j in myhost:
            m = j.replace("\n", "")
            myhosts.append(m)
    return myhosts


# 将系统hosts中已存在网站域名的删除
def del_host_from_syshosts():
    syshosts = read_syshosts()
    syshosts_new = [i for i in syshosts if i != '']
    # old_webmanager = list(filter(lambda text: all([word in text for word in webmanager]), syshosts_new))
    # old_www = list(filter(lambda text: all([word in text for word in www]), syshosts_new))
    inval = [text for word in web for text in syshosts_new if word in text]
    print("start check hosts ......")
    with open(hosts, 'w') as f_n:
        for line in syshosts_new:
            if line not in inval:
                f_n.write(line)
                f_n.write("\n")
            else:
                print(line + '  removed')
                continue


def add_host_from_hostconfig():
    print("\n")
    print("start add host......")
    hosts_config = read_host_config()
    syshosts = read_syshosts()
    for i in hosts_config:
        if i not in syshosts:
            with open(hosts, 'a') as tmp:
                tmp.write("\n")
                tmp.write(i)
                print('add  ' + i)
        else:
            print('already exist  ' + i)


if __name__ == '__main__':
    # 备份
    print("备份hosts文件为: " + hosts_bak)
    shutil.copy(hosts, hosts_bak)
    # 先删除多余的hosts
    del_host_from_syshosts()
    # 再添加需要的hosts
    add_host_from_hostconfig()
    subprocess.call('pause', shell=True)

  因为脚本是要给公司所有电脑执行的,所以将其打包即可,我使用的是pyinstaller打包的(注意添加管理员模式运行):

pyinstaller --uac-admin -F xxx.py

作者:likaifei

出处:https://www.cnblogs.com/likaifei/p/16706882.html

版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。

posted @   adai_kfl  阅读(2232)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
more_horiz
keyboard_arrow_up light_mode palette
选择主题
点击右上角即可分享
微信分享提示