#coding:utf-8
'''
Created on Oct 26, 2014

@author: root
'''
import commands
import socket
import struct

from PyQt4.QtCore import QString, QObject

import fcntl
from PyQt4.QtNetwork import QNetworkInterface, QHostInfo
import re


class ImacInfo(QObject):
    def __init__(self,parent=None):
        super(ImacInfo,self).__init__(parent)
        
    def get_Eth_Name(self):
        try:
            netcardList = "".join(commands.getstatusoutput("ls /sys/class/net")[1]).split("\n")
            validNetCardList = [netcard for netcard in netcardList if netcard not in ["br0", "lo", "breth0", "virbr0-nic", "virbr0"]]
            if len(validNetCardList)>0:
                return validNetCardList[0]
            else:
                return "enp2s0"
        except:
            return "enp2s0"
        
    #得到本机的MAC地址
    def get_mac_address(self): 
        cmd = "cat /sys/class/net/" + self.get_Eth_Name() + "/address"
        output = ""
        status = commands.getstatusoutput(cmd)
        if status[0] == 0:
            output = status[1]
        return output.upper()
    
    def getEthStatus(self):#返回一个网卡列表
        cmd = "ifconfig -a|awk '/Link encap/{print $1}'"
        output = ""
        statusOutput = commands.getstatusoutput(cmd)
        if statusOutput[0] == 0:
                output = statusOutput[1]
        else:
            output = ""
        result = output.split("\n")
        br = eth = 0
        for i in range(len(result)):
            if result[i] == "breth0":
                br = 1
            if result[i] == self.get_Eth_Name():
                eth = 1
        return br,eth
    
    #得到网卡的名称
    def getEthName(self):
        br,eth = self.getEthStatus()
        if br == 1 and eth == 1:
            return "breth0"
        elif br == 0 and eth == 1:
            return self.get_Eth_Name()
        else:
            return ""
                
    #得到本机的IP地址
    def get_ip_address(self):
        """create by pbc for get ipaddress method    2015.8.5 """
        try:
            localIp = self.get_local_ip()
            if localIp != "":
                return localIp
            
            ipaddr = socket.gethostbyname(socket.gethostname())
            if ipaddr != "127.0.0.1":
                return ipaddr
            else:
                try:
                    ifname = self.get_Eth_Name()
                    if ifname == "":
                        return "0.0.0.0"
                    s=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
                    ipd= socket.inet_ntoa(fcntl.ioctl(s.fileno(),
                                                      0X8915,
                                                      struct.pack('256s',ifname[:15]))[20:24])
                    return ipd
                except:
                    return "0.0.0.0"
        except:
            return "0.0.0.0"
    # 获取本机ip
    def get_local_ip(self):
        entNameList = "".join(commands.getstatusoutput("ls /sys/class/net")[1]).split("\n")    
        allowEntNameList = []
        for tempE in entNameList:
            if tempE in ["br0", "lo", "virbr0-nic", "virbr0"]:
                continue
            allowEntNameList.append(tempE)
        
        list = QNetworkInterface.allInterfaces()
        for interface in list:
            interfaceName = interface.name()
            if interfaceName in allowEntNameList:
                entryList = interface.addressEntries()
                for entry in entryList:
                    ip_str = str(entry.ip().toString())
                    pattern = r"\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b"
                    if re.match(pattern, ip_str):
                        return ip_str
        return ""   
                
                
        
    #得到CPU的信息
    def getCpuInfo(self):
        cpuInfo = None
        content = []
        statusOutput = commands.getstatusoutput("cat /proc/cpuinfo | grep name | cut -f2 -d: | uniq -c")
        if statusOutput[0] == 0:
            content = statusOutput[1].split("\n")
            if len(content) > 0:
                cpuInfo = content[0].strip().split("  ")[1] + " " + QString.number(len(content)) + " cores";
        return cpuInfo

    # 获取内存信息
    def getMemInfo(self):
        memInfo = None
        content = []
        statusOutput = commands.getstatusoutput("cat /proc/meminfo | grep MemTotal | awk '{print $2 $3}'")
        if statusOutput[0] == 0:
            content = statusOutput[1].split("\n")
            if len(content) > 0:
                memInfo = content[0]
        return str(int(memInfo.split("kB")[0])/1024)

    # test
    def mainGet(self):  
        print "MAC: ",(self.get_mac_address())
        print "ip_address: ",(self.get_ip_address())
        print "getCpuInfo: ",(self.getCpuInfo())
        print "getMemInfo: ",(self.getMemInfo())

if __name__ == "__main__":
    print "main"

    imacInfo = ImacInfo()
    imacInfo.mainGet()
    pass

