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 daemon守护进程实现

python daemon守护进程实现

假如写一段服务端程序,如果ctrl+c退出或者关闭终端,那么服务端程序就会退出,于是就想着让这个程序成为守护进程,像httpd一样,一直在后端运行,不会受终端影响。 守护进程英文为dae...

Python列表(list)常用操作方法小结

常见列表对象操作方法: list.append(x) 把一个元素添加到链表的结尾,相当于 a[len(a):] = [x] 。 list.extend(L) 将一个给定列表中的所有元素都...

python 如何快速找出两个电子表中数据的差异

最近刚接触python,找点小任务来练练手,希望自己在实践中不断的锻炼自己解决问题的能力。 公司里会有这样的场景:有一张电子表格的内容由两三个部门或者更多的部门用到,这些员工会在维护这些...

使用python 3实现发送邮件功能

下面一段简短代码给大家介绍python 3实现发送邮件功能,具体代码如下所示: import smtplib from email.mime.text import MIMEText...

Selenium鼠标与键盘事件常用操作方法示例

Selenium鼠标与键盘事件常用操作方法示例

本文实例讲述了Selenium鼠标与键盘事件常用操作方法。分享给大家供大家参考,具体如下: Selenium是一个用于Web应用程序测试的工具。Selenium测试直接运行在浏览器中,就...