getting remote ip in bash script

Charles Steinkuehler charles at steinkuehler.net
Thu Jan 30 21:56:33 CST 2003


Eric R. wrote:
> Hey LugNuts,
> 
> I'm trying to whip up a bash script that will report to the user at 
> logon, the logon id, IP they came from, etc.

<snip>

> I tried netstat, and piped it to cut -c45-65 but that gave me every 
> connection that netstat sees... LOL!!! not the desired effect!!

I needed to do this for a dynamic DNS type functionality (remote system 
logs into DNS server, and their IP is automatically updated in DNS).

I did this with ssh for authentication, and fought a while with trying 
to extract the remote IP before I finally came up with the following 
solution that works:

- Edit authorized keys file in ~/.ssh, and configure it to run a script:
command="bin/ip-update cruzin $SSH_CLIENT" 1024 35 11632...

NOTE: The $SSH_CLIENT variable is passed to the script...once the script 
runs, the environment variables set by ssh disappear, and I was unable 
to figure out any other means of extracting the remote IP (at least 
easily in a script...I could probably crawl through proc or something, 
but that seemed hard :)

- Write an approprite script :)  Mine run nsupdate to populate to update 
the IP of a remote client when they connect...allows dynamic DNS type 
behavior wrapped with the authentication flexability of ssh.  Note no 
input from the remote user is processed, making this update method 
fairly safe (as long as they don't keep finding more holes in ssh!).

<script>
#!/bin/sh

# Local settings:
# --------------------

KEYFILE="/var/named/keys/Kauburn.ks.newtek.com.+157+46294.private"
DOMAIN="ddns.newtek.com"
TTL=120

# --------------------

# Read name to update from argument list
HOST="$1"

[ -z "$HOST" ] && { echo "You MUST supply a hostname!" >&2; exit 1 ; }

# Read IP from argument list
IP="$2"

[ -z "$IP" ] && { echo "You MUST supply an IP!" >&2 ; exit 1 ; }

# Do the nsupdate
# NOTE:  There needs to be a blank line to send the update request...
nsupdate -k $KEYFILE >/dev/null <<- EOF
         server 127.0.0.1
         update delete $HOST.$DOMAIN A
         update add $HOST.$DOMAIN $TTL A $IP

         EOF
</script>

Of course, this isn't really doing exactly what you want, and will 
probably only work with ssh (you didn't mention if you're running ssh, 
telnet, rsh, or want a generic solution that would apply to everything), 
but I am extracting a remote IP and using it in a shell script, if it 
helps...

-- 
Charles Steinkuehler
charles at steinkuehler.net




More information about the Kclug mailing list