Airgiraffe
Airgiraffe

Reputation: 65

Run a script if no SSH connection

I'm trying to get a script to run at startup, but does nothing if I've connected to my Raspberry Pi via SSH.

So far I've got the crontab to automatically run the script checkssh.sh via @reboot sleep 30 && sudo bash ./checkssh.sh and './checkssh.sh' contains this:

#!/bin/bash

if [ -n "$SSH_CLIENT" ] || [ -n "$SSH_TTY" ]; then
  echo "SSH CONNECTED"
else
    ./autobackup.sh
fi

Running checkssh.sh from an SSH terminal returns 'SSH CONNECTED' which is expected, and letting it run automatically from the crontab at reboot when SSH isn't connected works correctly. However, when it runs at boot and I connect via SSH as soon as it's available, it still runs the script. I'm not sure where this is going wrong.

I need it to run automatically and if there's no SSH connection run autobackup.sh , but if there is an SSH connection, not to run anything. The device I use for the SSH connection may vary & the network used may also vary, so a script that relies on specific IP's isn't ideal.

Thanks for any help :)

Upvotes: 1

Views: 737

Answers (2)

Louis Papaloizou
Louis Papaloizou

Reputation: 282

Probably you need to add some delay before running your script to allow for the SSH service to come up. If cron service comes up before the sshd does, you will have a failure. Try:

@reboot sleep 60 && bash ./checkssh.sh

Also I would substitute the '.' with the full script path.
In one scenario I had to add as many as 120 seconds to get the @reboot crontab to work right. But ssh should not need as much. I guess you can trim 60 seconds according to your needs after you get it working.

Upvotes: 0

John Zwinck
John Zwinck

Reputation: 249394

Those environment variables (SSH_CLIENT and SSH_TTY) are only set in the environment of an SSH session. You cannot check them from another process and expect them to fulfill your goals here.

Instead, run the program finger. This is the standard way to see who is logged in.

Upvotes: 1

Related Questions