Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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)


share|improve this question
up vote 4 down vote accepted

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
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.

share|improve this answer
public key: Sep 27 08:49:04 host sshd[13816]: Accepted publickey for user from some_ip port 54966 ssh2 – Iain Sep 27 '10 at 9:21
For the archives: the log file is /var/log/auth.log in debian/ubuntu. – Scolytus Sep 27 '10 at 10:06
#client connecting from ${CLIENT_IP} to local ssh listening on SSHD_IP default port

A() {
  echo "A"
B() {
  echo "B"
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
    sleeptime=$((${sleeptime} - 1))
    sleep ${sleeptime}
kill -TERM `cat /var/run/`
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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