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将MongoDB里的ObjectId转换为时间戳的方法

本文实例讲述了python将MongoDB里的ObjectId转换为时间戳的方法。分享给大家供大家参考。具体分析如下: MongoDB里的_id字段前四位是时间戳的16进制表示,通过Py...

Python实现ping指定IP的示例

Python实现ping指定IP的示例

贴代码: import os import sys iplist = list() ip = '192.168.1.11' # ip = '172.24.186.191'...

pytorch使用 to 进行类型转换方式

pytorch使用 to 进行类型转换方式

在程序中,有多种方法进行强制类型转换。 本博文将介绍一个非常常用的方法:to()方法。 我们通常使用它来进行GPU和CPU的类型转换,但其实也可以用来进行torch的dtype转换。 常...

python代码 FTP备份交换机配置脚本实例解析

python代码 FTP备份交换机配置脚本实例解析

代码如下 #!/bin/python #coding=utf-8 #python-version=2.75 #使用python2 from ftplib impo...

Python中常用的8种字符串操作方法

Python中常用的8种字符串操作方法

拼接字符串 使用“+”可以对多个字符串进行拼接 语法格式: str1 + str2 >>> str1 = "aaa" >>> str2 = "b...