Chinaunix首页 | 论坛 | 博客
  • 博客访问: 28703519
  • 博文数量: 2065
  • 博客积分: 10377
  • 博客等级: 上将
  • 技术积分: 21525
  • 用 户 组: 普通用户
  • 注册时间: 2008-11-04 17:50
文章分类

全部博文(2065)

文章存档

2012年(2)

2011年(19)

2010年(1160)

2009年(969)

2008年(153)

分类: Python/Ruby

2010-07-21 21:43:35

# -*- encoding: utf-8 -*-
#整理Python采集不同平台下的硬件资源信息#
from ctypes import *
import os,time
class MEMORYSTATUS (Structure):
    _fields_ = [('dwLength', c_ulong),#sizeof(MEMORYSTATUS)
                ('dwMemoryLoad',c_ulong), # percent of memory in use
                ('dwTotalPhys', c_ulong),#;     // bytes of physical memory
                ('dwAvailPhys', c_ulong),#;     // free physical memory bytes
                ('dwTotalPageFile',c_ulong),#; // bytes of paging file
                ('dwAvailPageFile', c_ulong),#; // free bytes of paging file
                ('dwTotalVirtual', c_ulong),#;  // user bytes of address space
                ('dwAvailVirtual',c_ulong),#;  // free user bytes
    ]

if os.name == 'nt':
    mem = MEMORYSTATUS()
    memptr = pointer(mem)
    windll.kernel32.GlobalMemoryStatus(memptr)

    print "mem used",mem.dwMemoryLoad,"%"
    print "mem",mem.dwTotalPhys
    print mem.dwLength,mem.dwAvailPhys,mem.dwTotalPageFile,mem.dwAvailPageFile,mem.dwTotalVirtual
else:
    file = open('/proc/meminfo')
    conf = {}
    line = file.readline()
    while line:
        title, num, kb = line.split()
        conf[title[:-1]] = int(num)
        line = file.readline()
    file.close()
    print 'memtotal:', conf['MemTotal']
    print 'MemFree:', conf['MemFree']
    print 'Cached:', conf['Cached']
    print 'Buffers:', conf['Buffers']
    print 'SwapTotal:', conf['SwapTotal']
    print 'SwapFree:', conf['SwapFree']
    print 'mem%:',1-(conf['MemFree']*1.0/conf['MemTotal']), '%'
    print 'swap:',1-(conf['SwapFree']*1.0/conf['SwapTotal']), '%'
#################   CPU   #########################
SystemBasicInformation = 0
SystemPerformanceInformation = 2
SystemTimeInformation = 3
class LARGEINT(Union):
    class struct_1(Structure):
        _fields_ = [('lowpart', c_long),
                    ('highpart',c_long)
                    ]
    _fields_ = [("u", struct_1),
                ("QuadPart", c_longlong)]

class SYSTEM_BASIC_INFORMATION(Structure):
    _fields_ = [('dwOemId', c_ulong),
                  ('dwPageSize', c_ulong),
                  ('lpMinimumApplicationAddress', c_void_p),
                  ('lpMaximumApplicationAddress', c_void_p),
                  ('dwActiveProcessorMask', c_void_p),
                  ('dwNumberOfProcessors', c_ulong),
                  ('dwProcessorType', c_ulong),
                  ('dwAllocationGranularity', c_ulong),
                  ('wProcessorLevel', c_ushort),
                  ('wProcessorRevision', c_ushort),
                ]

class SYSTEM_PERFORMANCE_INFORMATION(Structure):
    _fields_ = [('liIdleTime', LARGEINT),
                ('dwSpare', c_ulong*76),
                ]

class SYSTEM_TIME_INFORMATION(Structure):
    _fields_ = [('liKeBootTime', LARGEINT),
                ('liKeSystemTime', LARGEINT),
                ('liExpTimeZoneBias', LARGEINT),
                ('uCurrentTimeZoneId', c_ulong),
                ('dwReserved', c_ulong),
            ]

if os.name=='nt':
    SysPerfInfo = SYSTEM_PERFORMANCE_INFORMATION ();
    SysTimeInfo = SYSTEM_TIME_INFORMATION ();
    SysBaseInfo = SYSTEM_BASIC_INFORMATION ();
    #get number of processors in the system
    windll.kernel32.GetSystemInfo(pointer(SysBaseInfo))
    windll.ntdll.NtQuerySystemInformation(SystemTimeInformation,
            pointer(SysTimeInfo),
            sizeof(SYSTEM_TIME_INFORMATION),
            0);
    windll.ntdll.NtQuerySystemInformation(SystemPerformanceInformation,
            pointer(SysPerfInfo),
            sizeof(SYSTEM_PERFORMANCE_INFORMATION),
            0);


    def Li2Double(x):
        return (((x).u.highpart) * 4.294967296E9 + ((x).u.lowpart))
        #return x.QuadPart

    liOldIdleTime = Li2Double(SysPerfInfo.liIdleTime);
    liOldSystemTime = Li2Double(SysTimeInfo.liKeSystemTime);
    begt = time.time()
    time.sleep(1)
    if SysPerfInfo.liIdleTime.QuadPart != 0:
        windll.kernel32.GetSystemInfo(pointer(SysBaseInfo))
        windll.ntdll.NtQuerySystemInformation(SystemTimeInformation,
                pointer(SysTimeInfo),
                sizeof(SYSTEM_TIME_INFORMATION),
                0);
        windll.ntdll.NtQuerySystemInformation(SystemPerformanceInformation,
                pointer(SysPerfInfo),
                sizeof(SYSTEM_PERFORMANCE_INFORMATION),
                0);
        # CurrentValue = NewValue - OldValue
        dbIdleTime = Li2Double(SysPerfInfo.liIdleTime) - liOldIdleTime;
        dbSystemTime = Li2Double(SysTimeInfo.liKeSystemTime) - liOldSystemTime;
        #print SysBaseInfo.dwNumberOfProcessors

        # CurrentCpuIdle = IdleTime / SystemTime
        dbIdleTime = dbIdleTime / dbSystemTime;

        # CurrentCpuUsage% = 100 - (CurrentCpuIdle * 100) / NumberOfProcessors
        dbIdleTime = 100.0 - dbIdleTime*100.0/SysBaseInfo.dwNumberOfProcessors ;

        print 'cpu used:',dbIdleTime,'%'

        liOldIdleTime = Li2Double(SysPerfInfo.liIdleTime);
        liOldSystemTime = Li2Double(SysTimeInfo.liKeSystemTime);
        time.sleep(1)
else:
    file = open('/proc/stat')
    line = file.readline()
    while not line.startswith('cpu'):
        line = file.readline()
    cpus = line.split()
    Totle1 = sum([int(i) for i in cpus[1:5]])
    use1 = sum([int(cpus[1]),int(cpus[2])])
    file.close()
    time.sleep(0.3)
    file = open('/proc/stat')
    line = file.readline()
    while not line.startswith('cpu'):
        line = file.readline()
    cpus = line.split()
    Totle2 = sum([int(i) for i in cpus[1:5]])
    use2 = sum([int(cpus[1]),int(cpus[2])])
    file.close()
    print 'cpuused:', (use2-use1)*1.0/(Totle2-Totle1)*100, '%'
####################获取磁盘信息##############################

####################获取网卡信息##############################

###################获取计算机名称#############################
def hostname():
    sys = os.name
    if sys == 'nt':
        hostname = os.getenv('computername')
        return hostname
    elif sys == 'posix':
        host = os.popen('echo $HOSTNAME')
        try:
            hostname = host.read()
            return hostname
        finally:
            host.close()
    else:
        return 'Unkwon hostname'
print "host name is",hostname()

##################获取硬盘相关资料############################

阅读(756) | 评论(1) | 转发(0) |
给主人留下些什么吧!~~

chinaunix网友2010-07-21 23:25:27

参考网站http://www.heniyiqi.com