tags:

views:

270

answers:

4

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?

+2  A: 

Your best bet is to use something like SSH and connect to the computer as root (or sudo in a system()), modify the file then disconnect. The added advantage of this is the convenience of prompting the user for the password.

To do this without prompting, the user would have to set up some means to accomplish it as root. I.e. setuid'ing a helper application, installing a password-less key, modifying a LDAP tree, or various other ways. That's a little 'icky' for the lack of a better term.

There's no way to make this work for user who does not normally have privilege escalation capabilities.

Tim Post
+1  A: 

You still must have the right permissions to edit the file.

To change the file, open the file in read/write/append mode (ie. mode "a" using fopen()) and write the new text to the end of the file.

Greg Hewgill
+2  A: 

Your program will need to be running with appropriate privileges. One of the classic techniques is to make the file owned by root and set the setuid bit. When your program is run, it will become root and will be able to modify /etc/hosts.

That said, setuid code is risky. A bug in the code can cause the program to do something so bad that your system becomes unuseable. Certain bugs can be used by malicious users to run arbitrary programs as root and take over your system.

R Samuel Klatchko
+1  A: 

I'm assuming you are at the command prompt, where you could issue that sudo command ..

Provided you have the access rights, as you claim you do, then any programming language that can add a line of text to an existing textfile (or create it, when not, which is unlikely), will work. You might habe to give that programm some additional rights, but that's a different topic!

Summary: what language do you know? => use that!

lexu