python切换hosts文件代码示例

yipeiwu_com6年前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实现AES和RSA加解密的方法

本文实例为大家分享了python实现AES和RSA加解密的具体代码,供大家参考,具体内容如下 AES AES 是一种对称加密算法,用key对一段text加密,则用同一个key对密文解密,...

Tensorflow实现酸奶销量预测分析

Tensorflow实现酸奶销量预测分析

本文实例为大家分享了Tensorflow酸奶销量预测分析的具体代码,供大家参考,具体内容如下 # coding:utf-8 # 酸奶成本为1元,利润为9元 # 预测少了相应的损失较大...

Python判断值是否在list或set中的性能对比分析

本文实例对比分析了Python判断值是否在list或set中的执行性能。分享给大家供大家参考,具体如下: 判断值是否在set集合中的速度明显要比list快的多, 因为查找set用到了ha...

linux查找当前python解释器的位置方法

先进入python 输入 import sys sys.executable 即可! 以上这篇linux查找当前python解释器的位置方法就是小编分享给大家的全部内容了,希望能给...

python+ffmpeg视频并发直播压力测试

通过python与ffmpeg结合使用,可生成进行视频点播、直播的压力测试脚本。可支持不同类型的视频流,比如rtmp或者hls形式。 通过如下方式执行脚本:python multiRe...