MacOS – How to automate launchctl / restart a daemon

automationlaunchdmacos

On OSX 10.10 I created a plist file in /Library/LaunchDaemons/ to start at launch an OpenVPN connection. However I encountered DNS problems when going from an internet interface to another (as WiFi to LAN Network) and thought that I needed to restart my OpenVPN daemon with launchctl to fix it.

But with this method I need to go to a console, type a monstrous launchctl's command with sudo and, of course, type my admin password.

Can this typing process be automated?

Edit

Thanks for @bmike general answer which will open new horizons and @Graham Miln though I'm not fond of AppleScript, but as @Mark requested here's my .plist file :

<?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>KeepAlive</key>
    <true/>
    <key>Label</key>
    <string>net.openvpnd</string>
    <key>ProgramArguments</key>
    <array>
        <string>/usr/sbin/openvpn</string>
        <string>/a/path/to/file.ext</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>SuccessfullExit</key>
    <true/>
    <key>StandardErrorPath</key>
    <string>/Library/Logs/ovpnerr.log</string>
    <key>StandardOutPath</key>
    <string>/Library/Logs/ovpn.log</string>
    <key>EnvironmentVariables</key>
    <dict>
      <key>PATH</key>
      <string>/usr/sbin:/another/path</string>
    </dict>
</dict>
</plist>

Best Answer

You could automate this process using AppleScript's do shell script … with administrator privileges command.

do shell script "command" user name "username" password "pass" with administrator privileges

The AppleScript can be saved as an application and launched as needed.

To avoid needing to embed administrator credentials within the AppleScript, omit the user name and password parameters. Without these parameters, you will be prompted to enter your credentials each time.

To avoid needing to authenticate each time, while also avoiding embedded credentials, you can investigate storing the credentials in your local Keychain and adding your AppleScript application to the Access Control list through Keychain Access.app.