Notice:

This page has been converted from a dynamic Wordpress article to a static HTML document. As a result, some content may missing or not rendered correctly.

SSH User's IP Address ~ Tue, 28 Jun 2011 13:45:24 +0000

Let's pretend you need to write a script that should not be run more than once concurrently. Let's also pretend that the script has the potential of being run by multiple people through the same account (wonderful security setup you have here). So you come up with the brilliant idea of making the script create a "I'm already running" file and check for it before continuing. If the file is already present, you decide that you want the script to tell the person trying to run it who is already running the script and quit. That's a bit tricky when everyone is logged in as the same user; you can't just output the username of the person running the script.  Everyone has a different IP address, though, so you can identify users by IP. So now you need to get the IP address of the person running the script. This is problem I had to solve.

Doing a little searching, I found a script using the who utility to solve this issue. The problem with that solution is that it relies on only one instance of the user being logged in. This solution doesn't account for multiple IP addresses in the output. A little more searching and I found a great answer, but it doesn't go all the way. So I expanded it into the following script (getIP):

#!/bin/bash

env_ssh_client=$(env | grep SSH_CLIENT | cut -d'=' -f2)

if [ "${env_ssh_client:0:1}" == ":" ]; then
    # IPv6 enabled
    # This is likely not nearly robust enough
    IP=$(echo ${env_ssh_client} | awk '{print $1}' | cut -d':' -f4)
else
    # IPv4 only
    IP=$(echo ${env_ssh_client} | awk '{print $1}')
fi

echo ${IP}

The script returns the IP address of the executing user. Pay attention to the comments. The system I'm using this on has IPv6 enabled, but uses dotted-quad notataion. Thus you might have to improve the script some for your own usage.

Bash,  Code,  Technology,  Tips