1

In my Python program (running on a Rasbian Pi, Linux), I'm changing values like the inet and the subnet with code like this:

os.system('sudo ifconfig eth1 %s netmask %s' % (self.controller.internet_inet_value.get(), self.controller.internet_mask_value.get()))

I'm NOT using this, though maybe I should...:

                '''subprocess.Popen(['sudo', 'ifconfig', 'eth1', '%s' % self.controller.internet_inet_value.get(),
                                  'netmask', '%s' % self.controller.internet_mask_value.get()])'''

for gateway I'm using:

gw_obj = subprocess.check_output(['sudo', 'route', 'add', 'default', 'gw', '%s' % self.controller.internet_default_gateway_value.get()]) #, stdout=subprocess.PIPE, shell=True
                                self.controller.internet_default_gateway_value2.set(self.controller.internet_default_gateway_value.get())

and my DNS values go something like this:

os.system('sudo ifconfig eth1 dns-nameservers %s %s %s' % (local_dns_var, local_dns_var2, local_dns_var3))

QUESTION: Is there a better way of doing this? These methods sort of work but I'm sure there must be a better way! I'd rather change these values at a python level instead of dipping into the OS. (These bits of code are obviously isolated from the rest).

3
  • Do you start your python program as root? There are some interfaces to change network settings programmatically, but it is much easier to use ifconfig or ip commands to do their job (if your code works and solves the task, it is already good enough). (Or just do correct setup of /etc/ files which stores network settings.)
    – osgx
    Jul 20, 2017 at 2:29
  • No, I didn't use root. I guess the code does work so I guess it's fine. Thanks, Osgx! Jul 20, 2017 at 13:37
  • When your python program is not root, it should use some kind of sudo & separate program to make changes to system settings like network settings. So, even when you have password-less sudo, you should fork to run sudo and other process as root. And in this case it is easier to use already written ifconfig/ip utils than rewrite them with python.
    – osgx
    Jul 20, 2017 at 14:40

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.