Hosts - file /etc/hosts

This parser parses the /etc/hosts file, strips the comments, ignores the blank lines, and collects the host names by IP address. IPv4 and IPv6 addresses are supported.

Sample hosts file:

127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
# The same IP address can appear more than once, with different names
127.0.0.1 fte.example.com

10.0.0.1 nonlocal.example.com nonlocal2.fte.example.com
10.0.0.2 other.host.example.com # Comments at end of line are ignored

Examples

>>> len(hosts.all_names)
10
>>> 'localhost6'in  hosts.all_names
True
>>> hosts.data['127.0.0.1']
['localhost', 'localhost.localdomain', 'localhost4', 'localhost4.localdomain4', 'fte.example.com']
>>> sorted(hosts.get_nonlocal().keys())
['10.0.0.1', '10.0.0.2']
>>> hosts.lines[-1]['ip']
'10.0.0.2'
>>> hosts.lines[2]['names']
['fte.example.com']
class insights.parsers.hosts.Hosts(context)[source]

Bases: Parser

Read the /etc/hosts file and parse it into a dictionary of host name lists, keyed on IP address.

property all_ips

The set of ip addresses known.

Type:

(set)

property all_names

The set of host names known, regardless of their IP address.

Type:

(set)

property data

The parsed result as a dict with IP address as the key.

Type:

(dict)

get_nonlocal()[source]

A dictionary of host name lists, keyed on IP address, that are not the ‘localhost’ addresses ‘127.0.0.1’ or ‘::1’.

ip_of(hostname)[source]

Return the (first) IP address given for this host name. None is returned if no IP address is found.

property lines

List of the parsed lines in the original order, in the following format:

{
    'ip': '127.0.0.1',
    'names': ['localhost', 'localhost.localdomain', 'localhost4', 'localhost4.localdomain4']
    'raw_line:' '127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4'
}
Type:

(list)

parse_content(content)[source]

This method must be implemented by classes based on this class.