Macos – Running a command line app with sudo and password automatically on OS X startup

applescriptbashcommand linemacosterminal

I need to run an app at startup/login on my mac. I want it to launch in the background and start doing it's work without interrupting me or me having to start it up because I invariably forget and then when I need it, it wasn't running!

I have tried using AppleScript to tell Terminal to run it and type my password in, but it ends up opening multiple Terminal windows and not working. Ideally I need a script that I can just add to the user login items and it will run for me.

The app has no way of taking a password argument either and it has a password as well as the sudo! I need a solution that can either be done as an applescript (which can be made into an executable) or i need a commandline script but I have no idea about them.

This is the manual code I type

$ sudo serverStatus
password:123456
password:serverpass

My AppleScript:

tell application Terminal
 activate
 do shell script "sudo serverStatus"
 delay 5
 do shell script "123456"
 delay 2
 do shell script "serverpass"
end tell

Best Answer

do shell script is used to execute shell scripts within an AppleScript and won't actually open a Terminal window. You could open a new Terminal window with do script and then emulate typing the passwords with keystroke.

tell application "Terminal"
    do script "sudo serverStatus"
    activate
end tell
delay 1
tell application "System Events"
    keystroke "login password" & return
    delay 1
    keystroke "server password" & return
end tell

If you're up for it, you could also just use a login hook which would be run after logging into your user account. This hook could call the appropriate AppleScript with:

osascript /path/to/script.scpt

But this seems to be a little too much if you could just add it to the login items manually.

Related Question