python获取ip地址
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import socket,fcntl,struct #crontab下shell命令无法执行 def getHostInfo(): # cmd = r"ifconfig|grep -v 127|grep 'inet addr' |awk '{print $2}'|cut -d : -f2" cmd = 'echo test' f = os.popen(cmd,'r') _ip = f.read().strip() f.close() return '事件源IP:%s\n运维用户:%s\n' %(_ip,os.getlogin()) def get_ip_address(ifname): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) inet = fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', ifname)) return socket.inet_ntoa(inet[20:24]) # mock socket connect def get_ip_socket(): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(('8.8.8.8', 80)) _ip = s.getsockname()[0] s.close() return _ip if __name__ == '__main__': # print getHostInfo() print '事件源IP:%s\n运维用户:%s\n' %(get_ip_address('eth6'),os.getlogin()) print get_ip_socket()