2

i want to restrict some website for getting open on osx. I can do it through terminal commands as:

sudo /Applications/TextEdit.app/Contents/MacOS/TextEdit /etc/hosts

then we can easly edit and save this file.just we can write local ip and website name to be restrict this website as 192.0.0.1 www.youtube.com. I want to do it programmatically, i tried as follows:

system("echo \"192.0.0.1 www.facebook.com\" >> /etc/hosts");
this application having root privileges still it is not able to append it and displaying permission denied message. can any one tell me what is the problem, or is there any other way to edit this file /etc/hosts

Faisal Ikwal
  • 703
  • 3
  • 8
  • 25

1 Answers1

0

With Apple Script you can do it like this.

do shell script "echo '192.0.0.1 www.facebook.com' >> /etc/hosts" with administrator privileges

From Objective-C you should use NSTask to run shell commands. See these two answers.

Instead of using a shell script, you could also natively write to the file using NSFileHandle. To know all the possibilities check out Apple's Authorization Services Programming Guide

Luke H
  • 3,125
  • 27
  • 31
orkoden
  • 18,946
  • 4
  • 59
  • 50
  • 1
    The `sudo` in this command is pointless. It applies to the left-hand side of the redirect (running the `echo`, which needs no elevated privileges) only. – nobody Oct 24 '14 at 12:51
  • @AndrewMedico I've removed the incorrect "sudo" from orkoden's answer. – Luke H Nov 11 '19 at 03:45