psn store 香港:Python

来源:百度文库 编辑:偶看新闻 时间:2024/05/09 07:02:55

Python-获得网卡Mac地址、出口ip

(2011-07-01 10:46:08)转载 标签:

python

mac

ip

it

分类: Python

#!/usr/bin/env python
#coding=utf-8
#get nic mac address use "ipconfig/ifconfig" ,another way useuuid.getnode()
#get Public network ip address use http://www.whereismyip.com
import os
import re
import sys
import urllib2

def GetMac():
    if os.name== 'nt':
       try:
           ret = ''
           CmdLine = 'ipconfig /all'
           r = os.popen(CmdLine).read()
           if r:
               L = re.findall('PhysicalAddress.*?([0-9,A-F]{2}-[0-9,A-F]{2}-[0-9,A-F]{2}-[0-9,A-F]{2}-[0-9,A-F]{2}-[0-9,A-F]{2})',r)
               if len(L) > 0:
                   ret = L[0]
       except:
           pass
       
    elif os.name== "posix":
       try:
           ret = ''
           CmdLine = 'ifconfig'
           r = os.popen(CmdLine).read()
           if r:
               L =re.findall('HWaddr.*?([0-9,A-F]{2}:[0-9,A-F]{2}:[0-9,A-F]{2}:[0-9,A-F]{2}:[0-9,A-F]{2}:[0-9,A-F]{2})',r)
               if len(L) > 0:
                   ret = L[0]
       except:
           pass
    else:
       pass
    returnret

import uuid

def get_mac():
    node =uuid.getnode()
    mac =uuid.UUID(int=node)
   sys.stdout.write(mac.hex[-12:]+"\n")
   


def get_ip():
    my_ip =re.search('\d+\.\d+\.\d+\.\d+',urllib2.urlopen("http://www.whereismyip.com").read()).group(0)
   sys.stdout.write(my_ip)

if __name__ == '__main__':
 

   mac =GetMac()
   sys.stdout.write(mac+"\n")
   get_mac()
   get_ip()