Handling Network Settings in Python

1

I work in linux environment, Python 2.7, and am needing a Python module / library that allows me to change the network settings (IP, Subnet, Gateway and, if possible, primary and secondary DNS).

I checked some libraries ( netaddr , ipaddress , netifaces , IPy ), but they only allowed me to read and do checks with the data of the network card (I was able to extract this information and show it on the screen) , but none allow me to make changes to this information.

My software should allow the user to leave the static IP on the machine, and to run os.system("") to change via terminal, I would need to be logged in as root.

If anyone knows of any way to make this kind of change, I will be eternally grateful.

    
asked by anonymous 08.02.2017 / 02:14

2 answers

2

I believe that pyroute2 is sufficient to meet your needs, I've played with it once, it's a very complete library, routes , create vlans , and many others, the script needs to run as root yes, since those changes require administrative privileges. on the Pypi site has some examples:

link

follows an example:

from pyroute2 import IPRoute
ip = IPRoute()

idx = ip.link_lookup(ifname='enp1s0')[0]

ip.link('set',
        index=idx,
        state='up')


ip.addr('add',
        index=idx,
        address='10.0.0.1',
        broadcast='10.0.0.255',
        prefixlen=24)

ip.close()
    
08.02.2017 / 15:02
1

I think this pyroute2 does what you're asking for.

If it does not work, and you can identify shell commands that do the configuration you need, using Python to run these commands might be better than trying to modify configuration files directly from Python (go give less work and and if you get wrong and generate a syntactically wrong file in your system settings will do much more work than if Python simply issue an invalid command)

The tip is, instead of using os.system , use the library subprocess Python - why it allows much more control of the external process, if you want to eg read what the external program prints in standard output and use those values in Python.

And last but not least - use Python 3 - whatever your Linux distribution, it will allow you to install Python3 in parallel to Python2 - Python2 had its last version in 2010, and it does not evolve anymore - in 3 years will stop being maintained, and if your code base is large, you'll have to port before that.

(And, yes, any script that goes like this needs to run as root. If you need it in the sudo documentation you can find ways that other users can only run your program with root privileges.)

    
08.02.2017 / 15:03