python指令碼修改hosts檔案

來源:互聯網
上載者:User

標籤:change   python   路徑   python指令碼   pyc   char   ==   源檔案   www.   

  用python3寫了個修改hosts的小指令碼,沒有技術含量,順帶複習一下檔案操作和os、sys模組的內容了。

 

# -*- coding:utf-8 -*- #!/usr/bin/env python# @Author  : tianbao# @Contact : [email protected]# @Time    : 2018/4/5 17:06# @File    : change_host_file.py# @Software: PyCharm‘‘‘使用說明:    PATH :HOSTS檔案路徑    NEW_PATH :新HOSTS檔案路徑        在change_host_file.py所在目錄開啟cmd運行以下命令                                     方法   IP        網址    添加:python change_host_file.py add 8.8.8.8 www.google.com    刪除:python hange_host_file.py del 126.125.66.198   刪除整行    修改:python hange_host_file.py change www.cnblogs.com www.google.com                                                 old              new‘‘‘import sys,os,rePATH = ‘G:\jiaoben\HOSTS‘NEW_PATH = ‘G:\jiaoben\HOSTS_NEW‘def run():    try:        if sys.argv[1] == ‘add‘:            with open(PATH,‘a+‘,encoding=‘utf-8‘) as f:                new_IP = sys.argv[2] + ‘ ‘+ sys.argv[3]                f.write(‘\n‘)                f.write(new_IP)                sys.exit(‘添加成功,請查看源檔案‘)        elif sys.argv[1] == ‘del‘:            with open(PATH, ‘r+‘, encoding=‘utf-8‘) as f,open(NEW_PATH, ‘a+‘, encoding=‘utf-8‘) as f2:                data = f.readlines()                for line in data:                    if sys.argv[2] in line:                        continue                    f2.write(line)            os.remove(PATH)            os.rename(NEW_PATH,PATH)            sys.exit(‘刪除成功,請查看源檔案‘)        elif sys.argv[1] == ‘change‘:            open(NEW_PATH, ‘a+‘).write(re.sub(r‘%s‘% sys.argv[2],‘%s‘% sys.argv[3],open(PATH).read()))            os.remove(PATH)            os.rename(NEW_PATH,PATH)            sys.exit(‘修改成功,請查看源檔案‘)    except Exception as e:        print(e)if __name__ == ‘__main__‘:    run()

  

python指令碼修改hosts檔案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.