开发手册 欢迎您!
软件开发者资料库

Python 使用 python-hosts 操作hosts文件(查找、增加和删除)

python-hosts 是管理hosts文件的 Python 库,它能够添加和删除hosts文件中的条目,或可以从文件或Url中导入内容。本文主要介绍使用python-hosts 操作hosts文件的方法,以及相关的示例代码。

1、安装引用python-hosts

pip install python-hosts

2、hosts文件中添加记录

通过python-hosts可以简单的添加内容到hosts文件中,如下

from python_hosts import Hosts, HostsEntryhosts = 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 Hostshosts = 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, HostsEntryhosts = 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, HostsEntryhosts = 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)