转载自http://www.blog.pythonlibrary.org/2010/02/06/more-windows-system-information-with-python/

How to Get Your Workstation’s Name

In this section, we’ll use the platform module to get our computer’s name. We actually mentioned this trick in my previous in my previous article, but since we need this information for the next snippet, I am going to repeat this trick here:

from platform import node
computer_name = node()

That was pretty painless, right? Only two lines of code and we have what we needed. But there’s actually at least one other way to get it:

import socket
computer_name = socket.gethostname()

This snippet is also extremely simple, although the first one is slightly shorter. All we had to do was import the builtin socket module and call its gethostname method. Now we’re ready to get our PC’s IP address.

How to Get the IP Address of Your PC with Python

We can use the information we garnered above to get at our PC’s IP address:

import socket
ip_address = socket.gethostbyname(computer_name)
# or we could do this:
ip_address2 = socket.gethostbyname(socket.gethostname())

In this example, we again use the socket module, but this time we its gethostbynamemethod and pass in the name of the PC. The socket module will then return the IP address.

You can also use Tim Golden’s WMI module. The following example comes from his wonderful WMI Cookbook:

import wmi
c = wmi.WMI ()
 
for interface in c.Win32_NetworkAdapterConfiguration (IPEnabled=1):
print interface.Description
for ip_address in interface.IPAddress:
print ip_address
print

All it does if loop over the installed network adapters and print out their respective descriptions and IP addresses.

How to Get the MAC Address with Python

Now we can turn our attention to getting the MAC address. We’ll look at two different ways to get it, starting with an ActiveState recipe:

def get_macaddress(host='localhost'):
""" Returns the MAC address of a network host, requires >= WIN2K. """
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/347812
import ctypes
import socket
import struct
 
# Check for api availability
try:
SendARP = ctypes.windll.Iphlpapi.SendARP
except:
raise NotImplementedError('Usage only on Windows 2000 and above')
 
# Doesn't work with loopbacks, but let's try and help.
if host == '127.0.0.1' or host.lower() == 'localhost':
host = socket.gethostname()
 
# gethostbyname blocks, so use it wisely.
try:
inetaddr = ctypes.windll.wsock32.inet_addr(host)
if inetaddr in (0, -1):
raise Exception
except:
hostip = socket.gethostbyname(host)
inetaddr = ctypes.windll.wsock32.inet_addr(hostip)
 
buffer = ctypes.c_buffer(6)
addlen = ctypes.c_ulong(ctypes.sizeof(buffer))
if SendARP(inetaddr, 0, ctypes.byref(buffer), ctypes.byref(addlen)) != 0:
raise WindowsError('Retreival of mac address(%s) - failed' % host)
 
# Convert binary data into a string.
macaddr = ''
for intval in struct.unpack('BBBBBB', buffer):
if intval > 15:
replacestr = '0x'
else:
replacestr = 'x'
if macaddr != '':
macaddr = ':'.join([macaddr, hex(intval).replace(replacestr, '')])
else:
macaddr = ''.join([macaddr, hex(intval).replace(replacestr, '')])
 
return macaddr.upper()

Since I didn’t write the code above, I won’t go into it in depth. However, it is my understanding that this script works by first checking to see if it can do an ARP request, which is only available on Windows 2000 and above. Once that’s confirmed, it attempts to use the ctypes module to get the inet address. After that’s done, it goes through some stuff that I don’t really understand to build the MAC address.

When I first started maintaining this code, I thought there had to be a better way to get the MAC address. I thought that maybe Tim Golden’s WMI module or maybe the PyWin32 package would be the answer. I’m fairly certain that he gave me the following snippet or I found it on one of the Python mailing list archives:

def getMAC_wmi():
"""uses wmi interface to find MAC address"""
interfaces = []
import wmi
c = wmi.WMI ()
for interface in c.Win32_NetworkAdapterConfiguration (IPEnabled=1):
if interface.DNSDomain == 'www.myDomain.com':
return interface.MACAddress

Unfortunately, while this method works, it slowed down the login script noticeably, so I ended up using the original method in the end. I think Mr. Golden has released a newer version of the wmi module, so it’s possible that this is now faster.

How to Get the Username

Getting the current user’s login name with Python is trivial. All you need is the PyWin32 package.

from win32api import GetUserName
userid = GetUserName()

One quick import and we have the username in two lines of code.

How to Find What Groups the User is in

We can use the userid we acquired above to find out what groups it’s in.

import os
from win32api import GetUserName
from win32com.client import GetObject
 
def _GetGroups(user):
"""Returns a list of the groups that 'user' belongs to."""
groups = []
for group in user.Groups ():
groups.append (group.Name)
return groups
 
userid = GetUserName()
pdcName = os.getenv('dcName', 'primaryDomainController')
 
try:
user = GetObject("WinNT://%s/%s,user" % (pdcName, userid))
fullName = user.FullName
myGroups = _GetGroups(user)
except Exception, e:
try:
from win32net import NetUserGetGroups,NetUserGetInfo
myGroups = []
groups = NetUserGetGroups(pdcName,userid)
userInfo = NetUserGetInfo(pdcName,userid,2)
fullName = userInfo['full_name']
for g in groups:
myGroups.append(g[0])
except Exception, e:
fullname = "Unknown"
myGroups = []

This is more intimidating than any of the previous scripts we looked at, but it’s actually pretty easy to understand. First we import the modules or method we need. Next we have a simple function that takes a user object as its sole parameter. This function will loop over that user’s groups and add them to a list, which it then returns to the caller. The next piece of the puzzle is getting the primary domain controller, which we use the os module for.

We pass the pdcName and userid to GetObject (which is part of the win32com module) to get our user object. If that works correctly, then we can get the user’s full name and groups. If it fails, then we catch the error and try to get the information with some functions from the win32net module. If that also fails, then we just set some defaults.

python获取windows信息的更多相关文章

  1. 关于Python 获取windows信息收集

    收集一些Python操作windows的代码 (不管是自带的or第三方库)均来自网上 1.shutdown 操作 定时关机.重启.注销 #!/usr/bin/python #-*-coding:utf ...

  2. 用python获取ip信息

    1.138网站 http://user.ip138.com/ip/首次注册后赠送1000次请求,API接口请求格式如下,必须要有token值 import httplib2 from urllib.p ...

  3. python 获取对象信息

    当我们拿到一个对象的引用时,如何知道这个对象是什么类型.有哪些方法呢? 使用type() 首先,我们来判断对象类型,使用type()函数: 基本类型都可以用type()判断: >>> ...

  4. Python 获取车票信息

    提示:该代码仅供学习使用,切勿滥用!!! 先来一个git地址:https://gitee.com/wang_li/li_wang 效果图: 逻辑: 1.获取Json文件的内容 2.根据信息生成URL ...

  5. 用python获取服务器硬件信息[转]

    #!/usr/bin/env python # -*- coding: utf-8 -*- import rlcompleter, readline readline.parse_and_bind(' ...

  6. python获取对象信息

    获取对象信息 拿到一个变量,除了用 isinstance() 判断它是否是某种类型的实例外,还有没有别的方法获取到更多的信息呢? 例如,已有定义: class Person(object): def ...

  7. python获取机器信息脚本(网上寻找的)

    获取机器信息(待测试) # -*- coding: UTF-8 -*- import psutil import json import os import socket import struct ...

  8. python获取的信息列表微信公共平台和用户头像

    转载注明原文地址:http://blog.csdn.net/btyh17mxy/article/details/25207889 只写模拟登陆的方式获取微信从信息和头像库列表公共平台, - 相关后,功 ...

  9. 使用 Python 获取 Windows 聚焦图片

    Windows 聚焦图片会定期更新,拿来做壁纸不错,它的目录是: %localappdata%\Packages\Microsoft.Windows.ContentDeliveryManager_cw ...

随机推荐

  1. 使用git遇到的一些问题

    上传github时忽略.DS_Store方法 这个文件在mac中是管理文件夹的位置之类的信息,所以并没有必要上传到git中,这个时候就需要用git.gitignore文件来忽略此类文件. 在默认情况下 ...

  2. C#中ICollection介绍

    ICollection 接口是 System.Collections 命名空间中类的基接口,ICollection 接口扩展 IEnumerable,IDictionary 和 IList 则是扩展 ...

  3. 持续集成CI相关的几个概念

    持续集成 https://en.wikipedia.org/wiki/Continuous_integration 为什么要持续? 持续集成, 可以避免集成地狱(由于工作的源码 和 库中的源码的差异导 ...

  4. PHP的核心配置详解

    1.PHP核心配置详解 代码在不同的环境下执行的结果也会大有不同,可能就因为一个配置问题,导致一个非常高危的漏洞能够利用:也可能你已经找到的一个漏洞就因为你的配置问题,导致你鼓捣很久都无法构造成功的漏 ...

  5. c++函数解析

    1.getline() 用getline读取文本 int main() { string line; getline(cin,line,'$');//'$'can change to other co ...

  6. Centos下查看mysql的版本

    判断是否安装了mysql 输入 whereis mysql   如果安装了会显示mysql的安装所在路径 方法1:使用mysql -v命令查看: 1 2 3 4 [root@yeebian mysql ...

  7. Python字符串方法总结(一)

    1.find 在一个较长的字符串中查找子串.它返回子串所在位置的最左端索引.如果没有找到则返回-1 2.split 将字符串用给定的分隔符分割成序列,当没有提供分隔符时,默认把所有空格作为分隔符 3. ...

  8. webpack学习笔记——--save-dev和--save

    --save-dev 是你开发时候依赖的东西,--save 是你发布之后还依赖的东西. dependencies是运行时(发布后)依赖,devDependencies是开发时的依赖 比如,你写 ES6 ...

  9. 牛客 被3整除的子序列dp

    题意很清楚,直接dp即可,dp[i][j]表示到第i个字符的状态为j的方案数,这里状态指的是子序列最大下标到第i直接dp即可,dp[i][j]表示到第i个字符的状态为j的方案数,这里状态指的是子序列最 ...

  10. Vi编辑器中全局替换

    1 例如下图 %s/hello/java/g #(等同于 :g/hello/s//java/g) 替换每一行中所有 hello 为 java 2 操作截图 替换所有的exec-avro-agent-L ...