There are several ways to accomplish this. One way is to put "it" in
rc.local, but that's hardly ever the best way to do it. Using
systemd is the new way, and perhaps the best way to do it, but not the simplest way. Using
cron is a third way, and that is what we shall try here.
Be forewarned: I usually try these things on my Pi before I put them in an answer, but I'm not going to do that in this case. Consequently, there may be a bit of "trial-and-error" to get this working. That said, here we go:
As always, you should be armed with some background before you begin copying and pasting, so please read, or briefly peruse, the following system manuals:
$ man cron # the daemon/service that makes all of this possible
$ man crontab # your instructions to cron
$ man 5 crontab # details on how to write crontab
If you've not used system manuals before, you type the letter
q to exit a man page & return to the CLI.
The version of
cron used in Raspbian provides a feature that allows us to start a program when the system boots. Here's how to use that:
$ crontab -e # "e" = edit; if prompted to select an editor - choose nano
You are now in the
nano editor. At the bottom of the file, add the following:
@reboot /bin/echo "System rebooted at: $(date)" >> /home/pi/mydatalog.txt 2>&1
nano, save the file, exit
nano & reboot your system. Afterwards, login again & find the file
mydatalog.txt in your (user pi I've assumed) home directory. Open it in
nano & verify the time you re-booted. If all this worked, you've just created a cron job that logs each system reboot to a file. If you're happy with this, leave it; if not use
crontab -e to change it, or delete the line entirely if you like.
In your question, you ask about running commands that require
root privileges to run. In this case, I feel it's best to use root's crontab instead of your own, but for Raspbian, this may not be necessary. Since this is my answer, we'll do it this way:
$ sudo crontab -e # opens root's crontab for editing
Note that root's crontab is a different
crontab as you will not see the line you added in the steps above. Enter the following in
@reboot /bin/sleep 30; /usr/sbin/service dhcpcd restart && /bin/sh -c "echo 1 > /proc/sys/net/ipv4/ip_forward" && /usr/sbin/iptables -t nat -A POSTROUTING -o wlan1 -j MASQUERADE && /usr/sbin/iptables -A FORWARD -i wlan1 -o eth0 -m state --state RELATED,ESTABLISHED -j ACCEPT && /usr/sbin/iptables -A FORWARD -i eth0 -o wlan1 -j ACCEPT && /usr/sbin/service dnsmasq start >> /home/pi/netsharelog.txt 2>&1
Save this file in
nano & exit. Now reboot your system. Let us know if you have any issues or questions.