Reputation: 991
I have two simple script that enables/disables Cisco AnyConnect when I don't want it trying to connect on each login/network transition. All was fine and dandy, but I wanted to add a line to the hosts file as well. The reason I'm using "echo $password | sudo -S" for most of the commands is because this script is being run from the script menu in Mac OS X. The terminal window does not open to address sudo password prompts.
#!/bin/bash
#Start_AnyConnect.command
password=`/usr/bin/osascript <<EOT
with timeout of (30 * 60) seconds
tell application "Finder"
activate
set myReply to text returned of (display dialog "Enter your password to authorize AnyConnect startup script" default answer "" with hidden answer)
end tell
end timeout
EOT`
echo $password | sudo -S echo -e "127.0.0.1\twpad.company.com" >> /etc/hosts
sleep 2
echo $password | sudo -S mv "/Library/LaunchAgents_Disabled/com.cisco.anyconnect.gui.plist" "/Library/LaunchAgents/com.cisco.anyconnect.gui.plist"
echo $password | sudo -S mv "/Library/LaunchDaemons_Disabled/com.cisco.anyconnect.vpnagentd.plist" "/Library/LaunchDaemons/com.cisco.anyconnect.vpnagentd.plist"
echo $password | sudo -S launchctl load /Library/LaunchDaemons/com.cisco.anyconnect.vpnagentd.plist
sleep 5
open /Applications/Cisco/Cisco\ AnyConnect\ Secure\ Mobility\ Client.app
exit 0
The problem I'm having is that
echo $password | sudo -S echo -e "127.0.0.1\twpad.company.com" >> /etc/hosts
appends "-e 127.0.0.1\twpad.company.com
" in stead of "127.0.0.1 wpad.company.com
" to the hosts file.
If I run the following command by itself it works as expected:
sudo echo -e "127.0.0.1\twpad.company.com" >> /etc/hosts
Is there another way to do this?
Thank you!
Upvotes: 3
Views: 6158
Reputation: 1489
This worked for me on OSX (last tested on Yosemite.) Hope it helps someone else!
sudo sh -c 'echo "127.0.0.1\twpad.company.com\n" >> /etc/hosts'
From the Macworld forums:
The actual explanation is that sudo invokes a subshell as root, and passes only it's first arg to that subshell to run.
Once the command finishes the subshell exits, and it's standard out is piped into >>. This attempts to open up and append to it's file argument as the original UID, which fails due to lack of privilege.
So, the solution is to pass the entire command line, including any redirects, so the whole thing is passed to sudo as one arg.
Upvotes: 7
Reputation: 359845
The version of echo
that is being run doesn't support -e
. When you use sudo
you get /bin/echo
rather than the shell's builtin echo
. Use printf
instead:
echo $password | sudo -S printf "127.0.0.1\twpad.company.com\n" >> /etc/hosts
Also, see the question linked to in Jaypal's comment regarding redirection and sudo
.
Upvotes: 5
Reputation: 28906
Edit or create the file '/etc/hosts.ac' to add your desired host entries. When you start AnyConnect, that file will replace '/etc/hosts'.
No scripted appending will be needed.
Upvotes: 1