1

I tried to get a script running at startup, but fail. crontab

@reboot /bin/sleep 8s && /bin/bash /home/user/reconnect.sh > /home/user/reconnect.log 2>&1

The script runs fine if I execute it by hand.

#!/bin/bash

If started as root, then re-start as user "user":

if [ "$(id -u)" -eq 0 ]; then exec sudo -H -u user $0 "$@" echo "This is never reached."; fi echo "This runs as user $(id -un)";

while [ "true" ] do VPNCON=$(/bin/nmcli con | /bin/grep PureVPN_PPTP | /bin/cut -f18 -d " ") if [[ $VPNCON != ens3 ]]; then /bin/echo "Disconnected, trying to reconnect..." (/bin/sleep 1s && /bin/nmcli con up uuid 1dfcb9f6-1b90-3d92-9f8b-106dc35da0f4) elif IP=$(ifconfig ppp0 | awk '/inet/{print $2; exit}') (/bin/sleep 5s) [ "$IP" != "xxx.xxxx.xxx.xxx" ]; then /bin/echo "wrong IP: $IP" (/bin/sleep 1s && /bin/nmcli con down uuid 1dfcb9f6-1b90-3d92-9f8b-106dc35da0f4 && /bin/sleep 2s && /bin/nmcli con up uuid 1dfcb9f6-1b90-3d92-9f8b-106dc35da0f4) else /bin/echo "Already connected !" fi /bin/sleep 30 done

Since the initial post, I have worked a little on the script. It works fine executed manually.

Executed by crone as user I get following error:

This runs as user user
Disconnected, trying to reconnect...
Error: Connection activation failed: Not authorized to control networking.

Somehow the user does with cron not have the same rights as by it selfe. The problem is, when executed as root it fails as well. The credentials for the vpn are stored in the users keyring, so root can't establish the connection:-/

Sturmkater
  • 11
  • 3

2 Answers2

1

Jobs run through cron, or systemd startup scripts aren't run in the same runtime environment that you have on your desktop. systemd startup scripts are run as root. None of your PATH changes, or other environment variable settings are automatically propagated to your cron job. For example, there's no $DISPLAY, so GUI programs need special treatment (read man xhost).

One can set environment variables for all one's cron jobs in the crontab file Read man 5 crontab.

Look at the results of echo "=== id ===";id;echo "=== set ===";set;echo "=== env ===";env | sort;echo "=== alias ===";alias in each of your environments.

Since the command part of the crontab line is, by default, interpreted by /bin/sh, which has a simpler syntax than /bin/bash, I recommend having command be a call to a bash script (executable, mounted, starts with #!/bin/bash) which sets up the environment, then calls the desired program.

waltinator
  • 36,399
0

Thanks, Steeldrive:-) I guess once you start with the GUI you are dammed to stick to it. Your suggestion works like charm.

@Sturmkater this sounds like something you should be doing via your user's startup applications, rather than via cron. See for example How do I start applications automatically on login? – steeldriver

Sturmkater
  • 11
  • 3