2

How to run a sudo on command line when a Mac startup?

Specifically, I'm trying to run the following line on Mountain Lion:

sudo ipfw add 100 fwd 127.0.0.1,8080 tcp from any to any 80 in

There are other questions about running command-line tools at startup (like this), but they do not address the issue of sudo and the required admin permissions/password.

Other Questions & Answers discuss launchd, but that seems to be for daemon processes that need to be watched and re-launched if crashed. In contrast, I am simply trying to do a one-off, run that one line once at startup.

If things have changed over the years, it would be nice to run a sudo at startup on both older versions of Mac OS X like Mountain Lion as well as newer like Yosemite/El Capitan.

3

although launchd and the term LaunchDaemon sounds like daemons, it is the preferred way to automate beneath everything. apple says in his documentation,

Login and logout scripts are a deprecated technology. In most cases, you should use launchd jobs instead, as described in Creating Launch Daemons and Agents

login and logout scripts are scripts which should run once and then end. they are triggered by loginwindow.

I think placing your command into a launchd plist file is the right way to do it. first, you can exclude launch agents, because they will run always as user. because you want the script run as root, you should place it under /Library/LaunchDaemons (/System/Library/LaunchDaemons would also work but system....) and add the flag RunAtLoad but don't set KeepAlive (or set it to something like crashed, see this good documentation).

EDIT because the script is running as root, you could omit the sudo, another option would be, create a script and include it in /etc/sudoers (visudo) with the nopasswd flag and run it as user

2

This question has some good answers over at apple.stackexchange.com.

cron is probably the easiest to set up; by using the special entry @reboot /path/to/script in the crontab file, your cronjob will only run at startup. There's an answer on how to do this in the question linked above.

launchd is probably the right solution here. You can use it to run one-off commands and scripts as well. One of the other answers in the question linked above deals with how to write a PropertyList-file for this. Note that the PropertyList must be placed under /Library/LaunchDaemons to run as root.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.