python切换hosts文件代码示例

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")

(0)

相关推荐

  • python逐行读取文件内容的三种方法

    方法一: 复制代码 代码如下: f = open("foo.txt")             # 返回一个文件对象  line = f.readline()             # 调用文件的 readline()方法  while line:      print line,                 # 后面跟 ',' 将忽略换行符      # print(line, end = '') # 在 Python 3中使用      line = f.readline()

  • 使用python的chardet库获得文件编码并修改编码

    首先需要安装chardet库,有很多方式,我才用的是比较笨的方式:sudo pip install chardet 复制代码 代码如下: #!/usr/bin/env python# coding: UTF-8import sysimport osimport chardet def print_usage(): print '''usage: change_charset [file|directory] [charset] [output file]\n for example:   cha

  • python解析文件示例

    python最近的工作主要是组件兼容性测试,原有的框架有很多功能还不完善,需要补充!比如,需要将AutoIt脚本的执行结果写入到Excel中,最后的解决方案是使用本地的log来解析这个结果! 增加了如下一个类来完成上述功能: 复制代码 代码如下: class AutoItResultParser():    def ParseResult(self, vm_result, log_file):        for case_result in vm_result.cases_results: 

  • python目录操作之python遍历文件夹后将结果存储为xml

    Linux服务器有CentOS.Fedora等,都预先安装了Python,版本从2.4到2.5不等,而Windows类型的服务器也多数安装了Python,因此只要在本机写好一个脚本,上传到对应机器,在运行时修改参数即可. Python操作文件和文件夹使用的是os库,下面的代码中主要用到了几个函数: os.listdir:列出目录下的文件和文件夹os.path.join:拼接得到一个文件/文件夹的全路径os.path.isfile:判断是否是文件os.path.splitext:从名称中取出一个子

  • python使用os模块的os.walk遍历文件夹示例

    复制代码 代码如下: #-*- coding:utf-8 -*- import os if __name__ == '__main__':    try:    '''traval and list all files and all dirs'''     for root, dirs, files in os.walk('D:' + os.sep + 'Python27'):        print '-------------------directory < ' + root + '

  • python删除文件示例分享

    删除文件 复制代码 代码如下: os.remove(   filename )   # filename: "要删除的文件名" 产生异常的可能原因: (1)filename 不存在(2)对filename文件, 没有操作权限或只读. 删除文件夹下所有文件和子文件夹 : 复制代码 代码如下: import os  def delete_file_folder(src):      '''delete files and folders'''     if os.path.isfile(s

  • python练习程序批量修改文件名

    复制代码 代码如下: # encoding:utf-8 ### 文件名如:# 下吧.mp3##import os,re fs=os.listdir('xb')for f in fs: ######方法一:partition获取无用字符 #1.将文件名以'['符分为3部分 #ls=f.partition('[') #2.ls[0]为需要文件名,因此获取ls[1:] #dirtystring = ''.join(ls[1:]) #3.开始替换 #newname=f.replace(dirtystri

  • 使用Python进行稳定可靠的文件操作详解

    考虑下述Python代码片段.对文件中的数据进行某些操作,然后将结果保存回文件中: 复制代码 代码如下: with open(filename) as f:   input = f.read()output = do_something(input)with open(filename, 'w') as f:   f.write(output) 看起来很简单吧?可能看起来并不像乍一看这么简单.我在产品服务器中调试应用,经常会出现奇怪的行为.这是我看过的失效模式的例子:失控的服务器进程溢出大量日志

  • 使用python将mdb数据库文件导入postgresql数据库示例

    mdb格式文件可以通过mdbtools工具将内中包含的每张表导出到csv格式文件.由于access数据库和postgresQL数据库格式上会存在不通性,所以使用python的文件处理,将所得csv文件修改成正确.能识别的格式. 导入脚本说明(此脚本运行于linux): 1.apt-get install mdbtools,安装mdbtools工具 2.将mdb 文件拷贝到linux虚拟机中,修改脚本中mdb文件目录'dir' 3.修改服务器及数据库配置 4.执行脚本 复制代码 代码如下: # -

  • python合并文本文件示例

    python实现两个文本合并 employee文件中记录了工号和姓名 复制代码 代码如下: cat employee.txt:100 Jason Smith200 John Doe300 Sanjay Gupta400 Ashok Sharma bonus文件中记录工号和工资 复制代码 代码如下: cat bonus.txt:100 $5,000200 $500300 $3,000400 $1,250 要求把两个文件合并并输出如下, 处理结果: 复制代码 代码如下: 400 ashok shar

  • python使用paramiko模块实现ssh远程登陆上传文件并执行

    程序执行时需要读取两个文件command.txt和ipandpass.txt.格式如下: 复制代码 代码如下: command.txt:ThreadNum:1port:22local_dir:hello_mkdirremote_dir:hello_mkdiralter_auth:chmod 755 hello_mkdirexec_program:./hello_mkdir ipandpass.txt:ip username password 程序中的队列操作是修改的别的程序,写的确实不错.该程序

  • 使用python统计文件行数示例分享

    复制代码 代码如下: import time def block(file,size=65536):    while True:        nb = file.read(size)        if not nb:           break        yield nb def getLineCount(filename):    with open(filename,"r",encoding="utf-8") as f:        return

  • python文件比较示例分享

    复制代码 代码如下: # 比较两个字符串,如果不同返回第一个不相同的位置# 如果相同返回0def cmpstr(str1, str2):    col = 0    for c1, c2 in zip(str1, str2):        if c1 == c2:            col += 1            continue        else :            break #判断是怎样退出循环的,还有一种情况是串长度不同    if c1 != c2 or le

  • Python批量修改文件后缀的方法

    近期下载了很多各种教程, 但是不幸的是后缀名都是 ".mp4", 而本人喜欢 ".rmvb" 后缀,由于有轻微洁癖, 受不了后面的 ".mp4" 缀, 但是手动修改又太过繁琐, 所以用近期刚学的 Python 来偷懒吧 !   : ) 如图为程序运行前的文件名 我们要做的呢, 就是在当前目录下,新建一个python文件, 如上图 demo2.py 然后用编辑器打开敲入如下代码: 复制代码 代码如下: import os # 列出当前目录下所有的文

  • python读文件逐行处理的示例代码分享

    复制代码 代码如下: import os ## for os.path.isfile() def dealline(line) :    print(line) ## 针对line我可以做很多事情 def getfilename() :    return input('Please input file name(input exit() for exit):').strip() class more : ## MORE功能    linenum = 0    size = 10    def

  • python文件读写并使用mysql批量插入示例分享(python操作mysql)

    复制代码 代码如下: # -*- coding: utf-8 -*-'''Created on 2013年12月9日 @author: hhdys''' import osimport mysql.connector config = {  'user': 'root',  'password': '******',  'host': '127.0.0.1',  'database': 'test',  'raise_on_warnings': True,}cnx = mysql.connect

  • 使用go和python递归删除.ds store文件的方法

    python版本: 复制代码 代码如下: #!/usr/bin/env pythonimport os, sys; def walk(path): print "cd directory:"+path for item in os.listdir(path): try: if(item == ".DS_Store"): global count count = count+1 print " find file .Ds_Store" os.rem

  • python实现批量转换文件编码(批转换编码示例)

    复制代码 代码如下: # -*- coding:utf-8 -*-__author__ = 'walkskyer' import osimport glob class Encoding:    def __init__(self):        #文件扩展名        self.ext = ".*"        #编码        self.srcEncoding=None        self.dstEncoding=None def convertEncoding(s

随机推荐