was: Re: how to autorun script at startup as administrator? but now a new problem

Colin Watson cjwatson at ubuntu.com
Tue Dec 31 00:22:42 UTC 2019


On Mon, Dec 30, 2019 at 03:06:57PM -0800, Dave Stevens wrote:
> My original post asked about running a privileged command at bootup.
> @reboot in the crontab does work for a non-privileged command but
> fails if the command is sudo <command>. Not very surprising but doesn't
> get me where I want to be.

If you put it in a root-owned crontab (either "crontab -e" as root with
the normal syntax, or /etc/crontab with an extra "root" field inserted
after the five time fields at the start of the line) then you don't need
to elevate privileges using "sudo".

> I've been reading about rc.local.

rc.local can technically be used for this sort of thing but it's not
really conventional nowadays; also, if you put something there then I
think the system's boot process will block until it's finished, which is
inappropriate given that you say you want to run an infinite-loop script
there.  While sshd ought to be running, it's a weird state to have the
system running in permanently.

> What I don't understand is whether it is correct that the script (if
> invoked through rc.local) will in fact run as root and if it does, will
> sshd be running at the time the (infinite loop) script is running.
> 
> The anticipated situation is that there's a power failure at a distant
> site where data collection is under way. I want a smooth recovery when
> power is restored, a new file started and data being captured.

Honestly it sounds like you'd be best off writing a little systemd
service to control this; that way if the script dies for some reason
other than a power failure (e.g. an out-of-memory event) then you can
arrange for it to be restarted.  What you're describing is conceptually
a service, and neither cron jobs nor rc.local are good at managing
those.

Something like this ought to do it, in e.g.
/etc/systemd/system/pollution-readings.service:

  [Unit]
  Description=Gather air pollution readings
  
  [Service]
  ExecStart=/path/to/your/script
  Restart=on-failure
  
  [Install]
  WantedBy=multi-user.target

Then "sudo systemctl enable pollution-readings.service" to arrange for
this service to start on boot, and "sudo systemctl start
pollution-readings.service" to start it immediately.  Obviously adjust
names to taste, and see systemd.service(5) for other settings you might
want to change in the [Service] section (I think the above should be
roughly right, but I haven't tested it).

-- 
Colin Watson                                       [cjwatson at ubuntu.com]




More information about the ubuntu-users mailing list