0

To learn about BASH scripting, I set myself the objective to write a Cron script which shuts down a PC with Mint 20 when activity on the Ethernet interface dropped below a threshold over an 1 hour. I mainly (but not exclusively) use the PC as File/DLNA Server. The script works, but now I find that it also shuts down the PC the rare times I'm using the the front end. So I want my script to verify if the screen has been blanked (As per Power Management settings)

To test the principle I included this in my script:

screenon=$(/usr/bin/xset -q | grep 'Monitor is' | cut -d "s" -f 2)}

which when run in a terminal window gives (debug: set -x)

screenon= On

but when run from cron gives. (logger)

/usr/bin/xset: unable to open display ""

I have learned about similar problems, but cannot figure out how to solve this.

My script includes:PATH=$PATH:/usr/local/bin

and my PATH is: /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin

Thanks in advance for any help.

Pete
  • 1
  • 2
  • 3
    `DISPLAY` variable is not set to point to the X server you are trying to query as would be when you run it under a user using current session. Even when you set it, you'll still have to handle authorization of process run under cron to access the X server in question. – Ondrej K. Apr 19 '21 at 10:01
  • To add to @OndrejK. comment, as it seems you're not familiar with X11, here is some tips : To authorize X11 server queries from other user id / host, use `xhost` commands in your X11 server init script. For the `DISPLAY` variable, you can use `xset -display [your display]` in your cron script. Check respective `xset` and `xhost` man pages. – Zilog80 Apr 19 '21 at 12:57
  • @Zilog80 I feel that recommending a novice X user uses `xhost` is a security disaster waiting to happen. If the cronjob is running as root, it is likely to suffice to run: `DISPLAY=:0 HOME=/path/to/frontenduser/home xset -q` (to find correct values, run `echo $DISPLAY; echo $HOME` as the frontent user) – jhnc Apr 20 '21 at 23:13
  • @jhnc You're right regarding security emphasis for `xhost` (I guess `xhost -` is now the default everywhere) . I'm anyway a little uneasy with altering HOME for shell scripts. Maybe something like `xauth extract - :0 | ssh root@localhost xauth merge -` in user .xserverrc would be sufficient here ? – Zilog80 Apr 21 '21 at 12:49
  • @Zilog80 if ssh to root works non-interactively, can't the shutdown cronjob just be run as the user? – jhnc Apr 21 '21 at 14:54
  • [this answer to another question](https://unix.stackexchange.com/a/117099/333919) shows a way to determine if a user other than the display manager is logged in. May need to alter the path to the X server. Not quite the same as testing if the monitor is on. – jhnc Apr 21 '21 at 14:56
  • @jhnc You are right. Why not then going for `crontab -u userid` and the `sudo` way :) – Zilog80 Apr 21 '21 at 16:22

0 Answers0