You could check if the process name of the script's parent pid matched
e.g. somewhere early in the script (immediately after the
#! line is a good place):
if [ "$(ps h -o comm -p "$PPID")" != "sshd" ] ; then
echo "This script can only be run directly from ssh." > /dev/stderr
This uses bash's built-in readonly variable "$PPID". It is automatically defined in every instance of bash.
Note that this is kind of pointless because anyone with read access to the script can just copy it and remove these few lines. The same will be true no matter what method the script uses to attempt this.
Also, process names are easily faked. It would be easy to write a wrapper script that set its process name to be
sshd before running your script.
If your concern is that other users may run your script, have you considered setting the permissions on the script so that only the script's owner can read or execute it? (e.g.
chmod 700 /path/to/script)