LaunchAgent以root身份运行bash脚本

时间:2014-04-08 16:18:09

标签: macos bash launch-agent

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.nords.locationchanger</string>
    <key>ProgramArguments</key>
    <array>
        <string>/usr/local/bin/locationChanger.sh</string>
    </array>
    <key>WatchPaths</key>
    <array>
        <string>/Library/Preferences/SystemConfiguration</string>
    </array>
</dict>
</plist>

LaunchAgent位于/ Library / LaunchAgents

如何让locationChanger.sh以root身份运行? 该脚本抛出错误,说它需要是root。如果我在需要root的行前面添加sudo,则会抛出一个错误,指出需要密码。

bash脚本中需要root的行是&#34; route add&#34;并删除&#34;

#!/bin/bash

exec 2> >(logger -t NETWORKSCRIPT)

location=$(networksetup -getcurrentlocation)
internalName="Internal"

if [ $location == $internalName ];
then
    echo "Internal Network!"
    logger -i "NETWORKSCRIPT CHANGE: Internal network, setting up custom routs and proxy stuff"
    git config --global http.proxy http://webproxysea.██████.net:8181
    route add -host 54.80.220.236 192.168.15.1
else
    echo "External Network!"
    logger -i "NETWORKSCRIPT CHANGE: $location network, removing custom stuff!"
    git config --global --unset http.proxy
    route delete -host 54.80.220.236 192.168.15.1
fi

1 个答案:

答案 0 :(得分:1)

超级用户解释:https://superuser.com/questions/36087/how-do-i-run-a-launchd-command-as-root

将您的.plist置于/Library/LaunchDaemonschown以root身份登录。