File: addr_default_ip.py

package info (click to toggle)
ddupdate 0.7.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 420 kB
  • sloc: python: 1,899; sh: 38; makefile: 35
file content (51 lines) | stat: -rw-r--r-- 1,336 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
"""
ddupdate plugin to obtain ip address.

See: ddupdate(8)
"""

import subprocess

from ddupdate.ddplugin import AddressPlugin, AddressError, IpAddr


def find_device(words):
    """Return first word following 'dev' or None."""
    found = False
    for word in words:
        if word == "dev":
            found = True
        elif found:
            return word
    return None


class DefaultIfPLugin(AddressPlugin):
    """
    Locates the default interface.

    Digs in the routing tables and returns it's address using linux-specific
    code based on the ip utility which must be in $PATH

    Options used: none
    """

    _name = 'default-if'
    _oneliner = 'Get ip address from default interface (linux)'

    def get_ip(self, log, options):
        """
        Get default interface using ip route and address using ifconfig.
        """
        if_ = None
        for line in subprocess.getoutput('ip route').split('\n'):
            words = line.split()
            if words[0] == 'default':
                if_ = find_device(words)
                break
        if if_ is None:
            raise AddressError("Cannot find default interface, giving up")
        address = IpAddr()
        output = subprocess.getoutput('ip address show dev ' + if_)
        address.parse_ifconfig_output(output)
        return address