1、安装引用python-hosts
pip install python-hosts
2、hosts文件中添加记录
通过python-hosts可以简单的添加内容到hosts文件中,如下
from python_hosts import Hosts, HostsEntry
hosts = Hosts(path='/etc/hosts')
new_entry = HostsEntry(entry_type='ipv4', address='1.2.3.4', names=['www.example.com', 'example'])
hosts.add([new_entry])
hosts.write()
#添加注释
new_entry_1 = HostsEntry(entry_type='comment', comment='# an example comment')
new_entry_2 = HostsEntry(entry_type='comment', comment='another example comment')
hosts.add(entries=[new_entry_1, new_entry_2], force=True)
hosts.write()
3、通过Url添加记录到hosts文件
可以将文件或者url中内容导入到hosts文件,如下,
from python_hosts import Hosts
hosts = Hosts(path='/etc/hosts')
hosts.import_url(url='https://gist.githubusercontent.com/jonhadfield/5b6cdf853ef629f9b187345d89157280/raw/ddfa4a069fb12bf3c1f285249d44922aeb75db3f/hosts')
hosts.write()
4、删除hosts文件中的记录
可以通过IP或域名,方便简单的删除hosts文件中内容,如下,
from python_hosts import Hosts, HostsEntry
hosts = Hosts(path='/etc/hosts')
new_entry = HostsEntry(entry_type='ipv4', address='1.2.3.4', names=['www.example.com', 'example'])
hosts.add([new_entry])
hosts.write()
#通过IP删除
hosts.remove_all_matching(address='1.2.3.4')
#通过域名删除
hosts.remove_all_matching(name='example.com')
hosts.write()
5、查找hosts文件中指定的记录
可以使用find_all_matching()方法,通过IP或域名查找hosts文件中的记录,如下
from python_hosts import Hosts, HostsEntry
hosts = Hosts(path='/etc/hosts')
new_entry = HostsEntry(entry_type='ipv4', address='1.2.3.4', names=['www.example.com', 'example'])
hosts.add([new_entry])
hosts.write()
#通过IP查找
ht = hosts.find_all_matching(address='1.2.3.4')
print(ht)
#通过域名查找
ht = hosts.find_all_matching(name='example.com')
print(ht)
#通过注释查找
ht = hosts.find_all_matching(comment='注释内容')
print(ht)