Wrapping python code for linux and windows in a script – best way?

  architecture, linux, python, scripting, windows

i like to write useful cli scripts for my colleagues at work and we have always the same problem with different operating systems. I found following question but in contrast to those solutions with higher frameworks like BeeWare I am seeking for very low level scripts which run on the cli and are very readable to all kind of python programmers. So I decided to create a use case and a sample ipchecker.py script which illustrates my preferred concept to share my recipes with my friends. The most useful case which everyone can profit from is to see the own IP addresses. Checkout MORE ON IPS PYTHON
I know there are lot of ways to check IPS but I want to do it in a way which can be seen as a general structure to add more komplex stuff in future … so lets start with this script:

[email protected] : pyton ipchecker.py # prints a list of my addresses

[email protected] : [‘192.168.178.11’, ‘172.18.1.9’, ‘172.00.0.1’, ‘2ak1:c22:c898:2d00:9788:6b0c:9ws2:4ss4’, ‘2a00:c32:c318:23d0:1a2c:23f5:4rs0:88r1’]

Is this a good way?

`

ipchecker.py

    import subprocess


    class LinuxIpChecker:
        """
        Only for linux
        """

        def __init__(self) -> None:
            self.runOnLinux()

        def runOnLinux(self):
            output = subprocess.check_output(['hostname', '-I'])
            addresses = [
                i for i in str(
                    output.decode(
                        'utf-8'
                    ).replace('n', '')
                ).split(' ') if len(i) > 0
            ]

            print(addresses)
            return addresses


    class IpChecker(object):
        """
        Just run and do not bother if windows or linux
        """

        def __init__(self) -> None:

            self.run()

        def run(self):
            try:
                self.runOnLinux()
                return
            except Exception as e:
                print(e)

            try:
                self.runOnWindows()
            except Exception as e:
                print('runOnWindows ::: n', e)

        def runOnLinux(self):

            output = subprocess.check_output(['hostname', '-I'])
            addresses = [i for i in str(output.decode(
                'utf-8'
            ).replace('n', '')).split(' ') if len(i) > 0
            ]

            print(addresses)
            return addresses

        def runOnWindows(self):
            addresses = []
            for i in self.getIPAddresses():
                print(i)
                addresses.append(i)

            return addresses

        def getIPAddresses():
            """
            credits to https://stackoverflow.com/users/18745/dzinx
            """
            from ctypes import Structure, windll, sizeof
            from ctypes import c_ulong, c_uint, c_ubyte, c_char
            from ctypes import POINTER, byref

            MAX_ADAPTER_DESCRIPTION_LENGTH = 128
            MAX_ADAPTER_NAME_LENGTH = 256
            MAX_ADAPTER_ADDRESS_LENGTH = 8

            class IP_ADDR_STRING(Structure):
                pass
            LP_IP_ADDR_STRING = POINTER(IP_ADDR_STRING)
            IP_ADDR_STRING._fields_ = [
                ("next", LP_IP_ADDR_STRING),
                ("ipAddress", c_char * 16),
                ("ipMask", c_char * 16),
                ("context", c_ulong)]

            class IP_ADAPTER_INFO (Structure):
                pass
            LP_IP_ADAPTER_INFO = POINTER(IP_ADAPTER_INFO)
            IP_ADAPTER_INFO._fields_ = [
                ("next", LP_IP_ADAPTER_INFO),
                ("comboIndex", c_ulong),
                ("adapterName", c_char * (MAX_ADAPTER_NAME_LENGTH + 4)),
                ("description", c_char * (MAX_ADAPTER_DESCRIPTION_LENGTH + 4)),
                ("addressLength", c_uint),
                ("address", c_ubyte * MAX_ADAPTER_ADDRESS_LENGTH),
                ("index", c_ulong),
                ("type", c_uint),
                ("dhcpEnabled", c_uint),
                ("currentIpAddress", LP_IP_ADDR_STRING),
                ("ipAddressList", IP_ADDR_STRING),
                ("gatewayList", IP_ADDR_STRING),
                ("dhcpServer", IP_ADDR_STRING),
                ("haveWins", c_uint),
                ("primaryWinsServer", IP_ADDR_STRING),
                ("secondaryWinsServer", IP_ADDR_STRING),
                ("leaseObtained", c_ulong),
                ("leaseExpires", c_ulong)]
            GetAdaptersInfo = windll.iphlpapi.GetAdaptersInfo
            GetAdaptersInfo.restype = c_ulong
            GetAdaptersInfo.argtypes = [LP_IP_ADAPTER_INFO, POINTER(c_ulong)]
            adapterList = (IP_ADAPTER_INFO * 10)()
            buflen = c_ulong(sizeof(adapterList))
            rc = GetAdaptersInfo(byref(adapterList[0]), byref(buflen))
            if rc == 0:
                for a in adapterList:
                    adNode = a.ipAddressList
                    while True:
                        ipAddr = adNode.ipAddress
                        if ipAddr:
                            yield ipAddr
                        adNode = adNode.next
                        if not adNode:
                            break


    if __name__ == '__main__':
        result = LinuxIpChecker()

`

Source: Windows Questions

LEAVE A COMMENT