Magazine

Python shell : extract the local IP from interface

Publié le 09 décembre 2008 par Theclimber

This is a small python script which can be used to extract the local IP address of a host in function of his interface. You can modify this script to adapt it to your purposes. ;)

#!/usr/bin/python
# Shell script scripts to read ip address
# -------------------------------------------------------------------------
# Copyright (c) 2008 Greg theClimber <http://www.theclimber.be/>
# This script is licensed under GNU GPL version 3.0
# -------------------------------------------------------------------------
from commands import *

os=getoutput('uname')
ifs=getoutput('ifconfig | grep "Ethernet" | grep -v "vnet" | cut --delimiter=L -f1').splitlines()
interfaces=[]

linux="ifconfig %s | grep 'inet adr:'| grep -v '127.0.0.1' | cut -d: -f2 | awk '{ print $1}'"
freebsd="ifconfig %s | grep -E 'inet.[0-9]' | grep -v '127.0.0.1' | awk '{ print $2}'"
sunos="ifconfig -a %s | grep inet | grep -v '127.0.0.1' | awk '{ print $2}'"

print "Please select the interface to use :"
for n, i in enumerate(ifs):
	i = i.rstrip(' ')
	interfaces.append(i)
	print "%s) %s" % (n, i)
print "default = 0"
try:
	num = input()
	num = int(num)
	i = interfaces[num]
except: num=0

addr=[]
if i:
	if os == 'Linux':
		ip = getoutput(linux % i)
	elif os =='FreeBSD':
		ip = getoutput(freebsd % i)
	elif os == 'SunOS':
		ip = getoutput(sunos % i)
	else:
		ip = "Unknown"
	print "%r:%r" % (i, ip)
	addr.append({'ip':ip,'if':i})

print {'addr':addr}

Retour à La Une de Logo Paperblog

A propos de l’auteur


Theclimber 25 partages Voir son profil
Voir son blog

l'auteur n'a pas encore renseigné son compte l'auteur n'a pas encore renseigné son compte

Dossier Paperblog