import _winreg:用python操作修改windows注册表

来源:互联网 发布:mac没有充电器怎么充电 编辑:程序博客网 时间:2024/06/04 23:29

 

用python操作修改windows注册表,显然要比用C或者C++简单。

   主要参考资料:官方文档:http://docs.python.org/library/_winreg.html

通过python操作注册表主要有两种方式,一种是通过python的内置模块_winreg,另一种方式就是Win32 Extension For Pythonwin32api模块。这里主要简单看看用内置模块_winreg如何操作注册表。

 

1.读取

读取用的方法是OpenKey方法:打开特定的key

_winreg.OpenKey(key,sub_key,res=0,sam=KEY_READ)

例子:此例子是显示了本机网络配置的一些注册表项

#!/usr/bin/env python

#coding=utf-8

 

import_winreg

 

key =_winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,                    r"SYSTEM/CurrentControlSet/Services/Tcpip/Parameters/Interfaces/{0E184877-D910-4877-B4C2-04F487B6DBB7}")

#获取该键的所有键值,遍历枚举

try:

   i=0

   while 1:

       #EnumValue方法用来枚举键值,EnumKey用来枚举子键

       name,value,type = _winreg.EnumValue(key,i)

       print repr(name),value,type

       i+=1

exceptWindowsError:

   print      

#假如知道键名,也可以直接取值

value,type =_winreg.QueryValueEx(key,"DhcpDefaultGateway")

print"默认网关地址----",value,type

 

运行的结果如下:

'UseZeroBroadcast' 0 4

'EnableDeadGWDetect' 1 4

'EnableDHCP' 14

'IPAddress'[u'0.0.0.0'] 7

'SubnetMask'[u'0.0.0.0'] 7

'DefaultGateway' [] 7

'DefaultGatewayMetric' [] 7

'NameServer'10.0.0.10 1

'Domain'  1

'RegistrationEnabled' 1 4

'RegisterAdapterName' 0 4

'TCPAllowedPorts' [u'0'] 7

'UDPAllowedPorts' [u'0'] 7

'RawIPAllowedProtocols' [u'0'] 7

'NTEContextList' [u'0x00000004'] 7

'DhcpClassIdBin' None 3

'DhcpServer'10.104.4.1 1

'Lease' 9072004

'LeaseObtainedTime' 1264122113 4

'T1' 12645757134

'T2' 12649159134

'LeaseTerminatesTime' 1265029313 4

'IPAutoconfigurationAddress' 0.0.0.0 1

'IPAutoconfigurationMask' 255.255.0.0 1

'IPAutoconfigurationSeed' 0 4

'AddressType' 04

'IsServerNapAware' 0 4

'DhcpIPAddress'10.104.5.15 1

'DhcpSubnetMask' 255.255.254.0 1

'DhcpRetryTime'453598 4

'DhcpRetryStatus' 0 4

'DhcpNameServer' 10.0.0.10 1

'DhcpDefaultGateway' [u'10.104.4.1'] 7

'DhcpSubnetMaskOpt' [u'255.255.254.0'] 7

 

默认网关地址---- [u'10.104.4.1'] 7

 

2.创建修改注册表

  创建key_winreg.CreateKey(key,sub_key)

  删除key:_winreg.DeleteKey(key,sub_key)

  删除键值: _winreg.DeleteValue(key,value)

原创粉丝点击