Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

Dynamically I want to edit/update hosts(etc/hosts) file to add domain.

To edit hosts(etc/hosts) file require Admin privileged. Using Linux I can do this by this command

sudo gedit /etc/hosts

But I am trying to do this from using Programming Language.

How can i do it?

share|improve this question

closed as off topic by Zoredache, womble, Nick Kavadias, splattne Oct 29 '09 at 21:35

Questions on Server Fault are expected to relate to professional server, networking, or related infrastructure administration within the scope defined by the community. Consider editing the question or leaving comments for improvement if you believe the question can be reworded to fit within the scope. Read more about reopening questions here.If this question can be reworded to fit the rules in the help center, please edit the question.

1  
If you need to be updating this frequently and dynamically, are you sure /etc/hosts is the right way? Perhaps you should consider running a DNS server that supports Dynamic updating instead? –  Zoredache Oct 29 '09 at 7:26
    
I am not that sure to work on /etc/hosts, but my purpose is to create Domain in the runtime programmability. Is there any other way to create a domain without using /etc/hosts? –  Anonymous Oct 29 '09 at 10:53
    
by editing /etc/hosts you are not "creating" a domain. You would be adding a hostname/ip pair, that then allows the local system to access that machine using the hostname in stead of the IP address. ..But then, you propably knew that.. –  lexu Oct 29 '09 at 17:19

2 Answers 2

Open the file from your program and use the standard faciliries for reading and writing text files. It's really no different from any other file out there.

And make sure your program runs as root so you can actually open and change that file.

share|improve this answer
    
@Johannes Rössel "your program runs as root". The problem is there? using "string shell_exec ( string $cmd )" in php I can execute shell command. BUT how about the privilege, I need to have admin privileged. –  Anonymous Oct 29 '09 at 9:18
    
@imrul: DONT RUN ANYTHING FROM A WEBSERVER WITH ADMIN RIGHTS ... calming down: seriously, this can/will allow a hacker to take over your system –  lexu Oct 29 '09 at 17:17

There's a project by RedHat called Augeas which provides a tree-like API for editing several kinds of common configuration files. The /etc/hosts file is one of those. There are bindings for numerous languages.

share|improve this answer