转载自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 socketmodule 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 socketmodule, but this time we its gethostbynamemethod and pass in the name of the PC. The socketmodule 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 osmodule 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 消息通讯_python获取windows信息相关推荐

  1. python windows 消息通讯_在windows下使用python进行串口通讯的方法

    在windows下使用python进行串口通讯的方法 Windows版本下的python并没有内置串口通讯的pyserial的库,所以需要自己下载.参照了网上的教程,有许多用的pip的安装方式,但是试 ...

  2. python查看开放的端口_python获取Windows端口信息

    # -*- coding: utf8 -*- ''' Windows的netstat显示很不友好 -anO能只能显示pid,没法看到program name -b能看出一些program name, ...

  3. python获取windows系统信息_Python获取Windows系统信息

    说明 本文主要引用两个库来完成对Windows基本信息的读取,读取信息包括CPU.磁盘.IP地址.安装的程序等. wmi 由于无法直接用pip进行安装,需要将下载过来的包解压后,在解压文件setup. ...

  4. python安装到桌面的路径是什么_Python 获取windows桌面路径的5种方法小结

    这里介绍了5中python获取window桌面路径的方法,获取这个路径有什么用呢?一般是将程序生成的文档输出到桌面便于查看编辑. 前两个方法是通过注册表来获取当前windows桌面绝对路径,比较推荐使 ...

  5. python文件名有空格_python 解决Windows平台上路径有空格的问题

    最近在采集windows上中间件的时候,遇到了文件路径有空格的问题. 例如:Aapche的安装路径为D:\Program Files\Apache Software Foundation\Apache ...

  6. python windows api截图_Python调用windows API实现屏幕截图

    Python调用windows API实现屏幕截图 好处是 灵活 速度快 缺点是: 写法繁琐 不跨平台 import time import win32gui, win32ui, win32con, ...

  7. python中如何写windows系统路径_Python在windows系统中表示文件路径

    Windows系统中,路径使用的是\.而Linux系统中,路径使用/.\同时也是转义字符,所以使用\的时候会有问题. 如果运气好,\后没有可以转义的字符,还是可以正常输出:print("C: ...

  8. python微信消息定时_python微信定时消息

    广告关闭 腾讯云11.11云上盛惠 ,精选热门产品助力上云,云服务器首年88元起,买的越多返的越多,最高返5000元! 使用supervisor的具体方法,在我这篇文章中有讲过:https:www.z ...

  9. python中的platform模块获取平台信息

    利用该模块可以获取系统平台与python平台的信息. import platform'''python中,platform模块给我们提供了很多方法去获取操作系统的信息如:import platform ...

最新文章

  1. 对NUnitAddIn做了下修改
  2. 【又放洋屁了】文艺细菌发作了
  3. 78万奖金!天池最新CV大赛来了
  4. IDEA中部署Tomcat设置访问路径
  5. i18n - why Chinese resource will be loaded by default
  6. 将G1内的SIM卡联系人导入到GMAIL的联系人中
  7. Mysql-my-innodb-heavy-4G.cnf配置文件注解
  8. usaco Cow Tours
  9. 135.002 智能合约设计-——多员工薪酬系统
  10. easydarwin 安装_win10安装EasyDarwin
  11. 假定我们要建立一个学术论文数据库,存储如下信息: •学术期刊有期刊编号、期刊名、发行单位; •作者有作者编号、作者姓名、电子邮件; •论文有论文编号、论文标题、摘要、正文; •每篇论文只被一个
  12. 嵌入式设计 | 基于51单片机的tea5767收音机设计实操教程
  13. 【评测】各种细胞治疗处理技术设备
  14. 淘宝数据库,主键如何设计以及自增ID的问题
  15. 第二章 03 藤蔓生长
  16. MSN、QQ、阿里旺旺在线客服源代码
  17. 在matlab中使用dsolve函数解范德波尔二阶微分方程
  18. python人脸识别门禁_Python+Opencv+Tkinter指纹识别与人脸识别的门禁兼考勤(二)
  19. XP桌面图标有蓝底/阴影 脑桌面有蓝色阴影如何去掉
  20. RabbitMQ内存消耗

热门文章

  1. 为什么SD-WAN5年增长超过40%,越来越受企业欢迎?
  2. 标签在MPLS网络中的功能—Vecloud
  3. sprintf,你知道多少?
  4. 树莓派 -- 按键 (key)使用BCM2835 gpio library
  5. JSP中两种include的区别
  6. jdbc中如何实现模糊查询
  7. Coreseek:部门查询和增量索引代替实时索引
  8. 在SQLite中使用事务
  9. Linux服务器程序编程的几个坎
  10. 本地数据源:使用firebird数据库