Ricardo Mogg
Ricardo Mogg

Reputation: 589

Any way to replace a DNS Server address in my /etc/resolv.conf using python in Ubuntu 12.04?

What is the best approach for developing a program in python that can replace an old DNS Server address for a new one in Ubuntu 12.04?

UPDATE: Basically what I need is a way to update my resolv.conf file content so that I can replace the nameservers configured in there.

So for example I have in my resolv.conf:

 nameserver 10.0.0.1
 nameserver 10.0.0.2

And I need to somehow modify to have the values:

 nameserver 10.0.0.3
 nameserver 10.0.0.4

I need to make this using python(or any scripting language or even by command line), because I need to do this in a user-friendly window that must run in a kiosk-mode Xubuntu.

**NOTE:

So far I have tried finding an ubuntu command that can achieve this, but I haven't found one.

I have also tried modifying /etc/resolv.conf but Python has no ability to modify a file, so I need to delete the file and create the file with the new content, however I have no permission to do this (already tried chmod 777 and chattr -a but they didn't work)

Upvotes: 0

Views: 2361

Answers (1)

larsks
larsks

Reputation: 311308

For this sort of editing task sed is often your best friend. To accomplish your example, the following would work:

sed -i '
  s/10\.0\.0\.1/10.0.0.3/
  s/10\.0\.0\.2/10.0.0.4/
' /etc/resolv.conf

This uses the search-and-replace operator, s//. The -i flag causes sed to modify the file in place, rather than printing the modified version on stdout.

Note that I am escaping the periods (.) in the match expression because in regular expressions, which sed uses for it's match syntax, the . character is a wildcard.

However, if you're simply switching between two different configurations, just replacing the file is probably the simplest solution:

cp /etc/resolv.conf.config1 /etc/resolv.conf

Upvotes: 1

Related Questions