0

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?

  • 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 07: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? –  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 Answers2

1

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.

Joey
  • 1,853
  • 11
  • 13
  • @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. –  Oct 29 '09 at 09: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
1

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.

Kamil Kisiel
  • 12,184
  • 7
  • 48
  • 69