python小工具之读取host文件

时间:2024-12-30 11:04:08
# -*- coding: utf-8 -*-
# @Time : 2018/9/12 21:09
# @Author : cxa
# @File : readhostfile.py
# @Software: PyCharm
import platform as p
import os
# print(os.system())
p1 = p.system()
path = 'C:\Windows\System32\drivers\etc'
os.chdir(path)
file = 'hosts' def read_hosts():
with open(file, 'r') as fs:
data = fs.readlines()
return data if __name__ == '__main__':
if p1 == "Windows":
datas = read_hosts()
for data in datas:
print(data)

  

因为直接读hosts文件没有权限所以使用了以下方法。

path = 'C:\Windows\System32\drivers\etc'
os.chdir(path)
file = 'hosts'