系统补丁的文件名类似于这样:"WindowsServer2003-KB924667-v2-x86-CHS.exe",为了过滤出其中的KB号,我用以下方法:
ab = "WindowsServer2003-KB924667-v2-x86-CHS"
res = ab.split("-")
res1 = res[1].split("KB")
print res1[1]
split()把字符串分割成列表,通过两次分割,得到KB号。
唐唐给出更精简的代码:
ab = "WindowsServer2003-KB924667-v2-x86-CHS"
res = filter(str.isdigit,ab.split("-")[1])
filter(function, iterable)是python内置函数,它根据function参数返回的结果是否为真来过滤list参数中的项,最后返回一个新列表。官方文档:
http://docs.python.org/library/functions.html#filter
str.isdigit是系统内建的字符串方法,如果字符串全部是数字就返回true,官方文档在这里:http://docs.python.org/library/stdtypes.html
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
在程序里得到系统已经安装的补丁列表:
# 得到系统已经安装的补丁的KB号
p = os.popen("wmic qfe get hotfixid")
patch1 = p.read()
for i in patch1.split('\r\n'):
i = i.lstrip("KB") # 去掉开头的"KB"
patched.append(i.strip())
输出结果:
['HotFixID', '982861', '2305420', '2393802', 982018', '', '']
再要把其中的'HotFixID和后面2个空字符串去掉,在程序中加入判断语句:
# 得到系统已经安装的补丁的KB号
p = os.popen("wmic qfe get hotfixid")
patch1 = p.read()
for i in patch1.split('\r\n'):
if (cmp(i.strip(), "HotFixID") != 0) and (cmp(i, "") != 0):
i = i.lstrip("KB")
patched.append(i.strip())
print patched
注:wmic输出字符串的时候,每行后面都有空格,所以在比较的时候,要用strip()把空格去掉。
现在的输出:['982861', '2305420', '2393802', 982018]'