python3 写法
#!/usr/bin/env python
#-- coding:utf-8 --

import socket
import fcntl,struct
import time

def getHardware(outip,inip):
sk = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
##1.获取主机名
hostname = socket.gethostname()
print ('主机名*****',hostname)

##获取ip,
OutIp = socket.inet_ntoa(fcntl.ioctl(sk.fileno(), 0x8915, struct.pack('256s', bytes(outip[:15],'utf-8')))[20:24])
InIp = socket.inet_ntoa(fcntl.ioctl(sk.fileno(), 0x8915, struct.pack('256s', bytes(inip[:15],'utf-8')))[20:24])
print ('外网网卡为*************************',OutIp)
print ('内网网卡为*************************',InIp)

#填写网卡名称,我这里没有外网ip,用lo测试
getHardware('eth0','eth1')

python2 方法
#!/usr/bin/env python
#-- coding:utf-8 --

author:Zeng Xianhe

import socket
import fcntl,struct
import time

def getHardware(outip,inip):
sk = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
##1.获取主机名
hostname = socket.gethostname()
print '主机名*****',hostname

##获取ip,
OutIp = socket.inet_ntoa(fcntl.ioctl(sk.fileno(), 0x8915, struct.pack('256s', outip[:15]))[20:24])
InIp = socket.inet_ntoa(fcntl.ioctl(sk.fileno(), 0x8915, struct.pack('256s', inip[:15]))[20:24])
print '外网网卡为*************************',OutIp
print '内网网卡为*************************',InIp

#填写网卡名称,我这里没有外网ip,用lo测试
getHardware('lo','eth0')