Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

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

share|improve this question

2 Answers 2

up vote 3 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
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.

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"
}
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
share|improve this answer

Your Answer

 
discard

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.