2

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?

3
  • 1
    This file is highly 'guarded' by newer OSes and security/anti-virus software, just for info :) Commented Oct 29, 2009 at 7:12
  • Duplicate: serverfault.com/questions/79399/… Commented Oct 29, 2009 at 7:28
  • @Randolph Potter: This is also asked by me, serverfault.com/questions/79399/… Commented Oct 29, 2009 at 10:32

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

1

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.

Comments

1

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!

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.