天天看點

利用Python腳本擷取Windows和Linux的系統版本資訊

    檢視系統版本資訊是一件家常便飯的事情,有時候需要将版本資訊錄入到資産管理系統中,如果每次手動的去查詢這些資訊再錄入系統那麼是一件令人呢頭疼的事情,如果采用腳本去完成這件事情,那麼情況就有所不同了。

    在Python的世界裡,擷取Windows版本資訊和Linux的版本資訊都可以采用platform子產品,但platform子產品也不是萬能的,有些特殊的資訊(比如Windows的内部版本号)這個子產品拿不到,那麼隻能另辟蹊徑了。

    在Linux系統中,可以簡單的認為一切都是檔案,那麼就算沒有現成的指令可用時,可以用open()檔案的方法通過對檔案的讀寫控制它。而在Windows的大部分資訊在系統資料庫中都能查到,是以可以從系統資料庫上下手。Windows系統資料庫是一個好東西,拿資料就像在Linux下一切都是檔案一樣友善,如果想用Python通路系統資料庫,除了權限外就是需要子產品了,在Python中_winreg是一個内置子產品,通過這一子產品可以對系統資料庫進行讀寫。

    本腳本收集了一些擷取版本資訊的常見方法,除了platform子產品外,還有其他的子產品可供使用,因為platform子產品不是内置子產品,是以需要額外安裝。Windows下運作腳本需要考慮權限問題和中文字元的問題,解決Python列印中文字元的問題是通過腳本中的get_system_encoding()函數實作的,這個函數取自Django,經過測試這個函數還是非常好用的。

    注:在PyCharm中,經常遇到Run視窗列印出的中文顯示亂碼,代碼中沒有經過正确轉碼是一方面,而IDE的編碼設定也是一方面。如果是在Windows下開發,那麼建議代碼用UTF-8編寫,IDE的編碼則設定為“GBK”,設定方法“File”-->"Settings"-->"Editor"-->"File Encoding"-->"IDE Encoding"選擇“<System Default (now GBK)>”, "Project Encoding"選擇UTF-8保證代碼的編碼一緻性。

利用Python腳本擷取Windows和Linux的系統版本資訊
腳本如下:

#!/usr/bin/python
# encoding: utf-8
# -*- coding: utf8 -*-
"""
Created by PyCharm.
File:               LinuxBashShellScriptForOps:getSystemVersion.py
User:               Guodong
Create Date:        2016/12/16
Create Time:        14:51
 """
import sys
import os
import platform
import subprocess
import codecs
import locale


def get_system_encoding():
    """
    The encoding of the default system locale but falls back to the given
    fallback encoding if the encoding is unsupported by python or could
    not be determined.  See tickets #10335 and #5846
    """
    try:
        encoding = locale.getdefaultlocale()[1] or 'ascii'
        codecs.lookup(encoding)
    except Exception:
        encoding = 'ascii'
    return encoding


DEFAULT_LOCALE_ENCODING = get_system_encoding()

mswindows = (sys.platform == "win32")  # learning from 'subprocess' module
linux = (sys.platform == "linux2")

hidden_hostname = True

if mswindows:
    uname = list(platform.uname())
    if hidden_hostname:
        uname[1] = "hidden_hostname"
    print uname

    import _winreg

    try:
        reg_key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion")
        if reg_key:
            ProductName = _winreg.QueryValueEx(reg_key, "ProductName")[0] or None
            EditionId = _winreg.QueryValueEx(reg_key, "EditionId")[0] or None
            ReleaseId = _winreg.QueryValueEx(reg_key, "ReleaseId")[0] or None
            CurrentBuild = _winreg.QueryValueEx(reg_key, "CurrentBuild")[0] or None
            BuildLabEx = _winreg.QueryValueEx(reg_key, "BuildLabEx")[0][:9] or None
            print (ProductName, EditionId, ReleaseId, CurrentBuild, BuildLabEx)
    except Exception as e:
        print e.message.decode(DEFAULT_LOCALE_ENCODING)

if linux:
    uname = list(platform.uname())
    if hidden_hostname:
        uname[1] = "hidden_hostname"
    print uname

    proc_obj = subprocess.Popen(r'uname -a', shell=True, stdout=subprocess.PIPE,
                                stderr=subprocess.STDOUT)
    result = proc_obj.stdout.read().strip().decode(DEFAULT_LOCALE_ENCODING)
    if result:
        print result

    if os.path.isfile("/proc/version"):
        with open("/proc/version", 'r') as f:
            content = f.read().strip()
        if content != "":
            print content

    if os.path.isfile("/etc/issue"):
        with open("/etc/issue", 'r') as f:
            content = f.read().strip()
        if content != "":
            print content      

注:腳本内容可以通過GitHub擷取,位址:https://github.com/DingGuodong/LinuxBashShellScriptForOps/blob/master/functions/system/getSystemVersion.py:。

截圖如下:

(1)系統資料庫資訊擷取位置:

利用Python腳本擷取Windows和Linux的系統版本資訊

(2)Windows環境下的輸出:

利用Python腳本擷取Windows和Linux的系統版本資訊

(3)Linux環境下的輸出: