python切换hosts文件代码示例

yipeiwu_com5年前Python基础

win7以上需要使用管理员权限操作。

复制代码 代码如下:

# -*- coding: utf-8 -*-
import os
import glob
import shutil

def format_file_list(files):
        all_files_str = ""
        for i in range(len(files)):
                all_files_str +=  str(i)+":"+files[i]+"\n"
        return all_files_str

hosts_path = "C:\\Windows\\System32\\drivers\\etc"
files =  os.listdir(hosts_path)
os.chdir(hosts_path)

if os.getcwd() != hosts_path:
        print("Switch Dir to System32 Error,check permission!\npwd:"+os.getcwd())
        exit()

hosts_files = glob.glob("host*")
choosed_file_idx = int(input("Choose Hosts File Index:\n"+format_file_list(hosts_files)))
files_num = len(hosts_files)

if (choosed_file_idx < 0 or choosed_file_idx >= files_num) :
        print("Please choose a file in the lists!")
        exit()

print("Choosed idx:{0},file:{1}.".format(choosed_file_idx,hosts_files[choosed_file_idx]))
shutil.copy("hosts","hosts.bak")
shutil.copy(hosts_files[choosed_file_idx],"hosts")
print("Copy ok,then flush dns...")
os.system("ipconfig /flushdns")

相关文章

Python中使用scapy模拟数据包实现arp攻击、dns放大攻击例子

scapy是python写的一个功能强大的交互式数据包处理程序,可用来发送、嗅探、解析和伪造网络数据包,常常被用到网络攻击和测试中。 这里就直接用python的scapy搞。 这里是ar...

使用pycharm生成代码模板的实例

通过在File->setting->File and Code Templates设置模板代码,这样就可以在新建python文件的时候自动带上抬头。 # -*- codi...

python文本数据处理学习笔记详解

python文本数据处理学习笔记详解

最近越发感觉到限制我对Python运用、以及读懂别人代码的地方,大多是在于对数据的处理能力。 其实编程本质上就是数据处理,怎么把文本数据、图像数据,通过python读入、切分等,变成一个...

OpenCV+python手势识别框架和实例讲解

OpenCV+python手势识别框架和实例讲解

基于OpenCV2.4.8和 python 2.7实现简单的手势识别。 以下为基本步骤 1.去除背景,提取手的轮廓 2. RGB->YUV,同时计算直方图 3.进行形态学滤波,提...

python使用tornado实现登录和登出

本文实例为大家分享了tornado实现登录和登出的具体代码,供大家参考,具体内容如下 main.py如下: import tornado.httpserver import torn...