2

For some reason I have he following scenario:

On boot-up I'm launching a script which waits for a given amount of time and checks whether an SSH connection was astablished during this time window or not. If a connection is open, the script does action A, else it kills sshd and does B.

What would be the best way to detect an open connection? (The script can be written in Bash or Ruby)

thx

2 Answers 2

6

If you want to detect a current SSH session, use lsof -i :22 and look for it returning more than 2 lines or grep for ESTABLISHED:
[root@nemo ~]# lsof -i :22
COMMAND PID USER FD TYPE DEVICE SIZE NODE NAME
sshd 3772 root 3u IPv6 9906 TCP *:ssh (LISTEN)
sshd 21376 root 3r IPv6 159072 TCP myserver:ssh->someip:27813 (ESTABLISHED)
sshd 21381 james 3u IPv6 159072 TCP myserver:ssh->someip:27813 (ESTABLISHED)

To see if a session was opened at all, look for something similar to the following in /var/log/secure (on redhat/centos/fedora):
Sep 27 05:05:28 nemo sshd[21376]: Accepted password for james from some_ip port 27813 ssh2
If you allow authentication by means other than password, the log entries may be slightly different.

4
  • public key: Sep 27 08:49:04 host sshd[13816]: Accepted publickey for user from some_ip port 54966 ssh2
    – user9517
    Sep 27, 2010 at 9:21
  • For the archives: the log file is /var/log/auth.log in debian/ubuntu.
    – Scolytus
    Sep 27, 2010 at 10:06
  • Fairly new to linux, but it seems to me something like this might work quite well to get a list of unique connections. Please correct me if I am wrong! sudo lsof -i :22 | grep -Po '(?<=TCP ).*(?= \(ESTABLISHED\))' | uniq It could be adjusted to use | wc -l on the end for a connection count.
    – mrswadge
    Nov 1, 2017 at 0:07
  • This one checks for outgoing ssh connections.
    – jamadagni
    Oct 6, 2019 at 15:19
3
#client connecting from ${CLIENT_IP} to local ssh listening on SSHD_IP default port

A() {
  echo "A"
}
B() {
  echo "B"
}
CLIENT_IP=""
SSHD_IP=""
sleeptime=5 #use this counter to sleep $sleeptime seconds, decrementing on match fail
while [ ${sleeptime} -gt 0 ] ; do
  netstat -nt |grep -q -E "${CLIENT_IP}:[0-9]+[[:space:]]+${SSHD_IP}:22[[:space:]]+ESTA"
  if [ $? -eq 0 ] ; then 
    A; exit 0
  else
    sleeptime=$((${sleeptime} - 1))
    sleep ${sleeptime}
  fi
done
kill -TERM `cat /var/run/sshd.pid`
B
1
  • This one checks for incoming ssh connections.
    – jamadagni
    Oct 6, 2019 at 15:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.