|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
小知识:Linux同时也提供了类似Windows图形界面的X-Window系统,用户可以使用鼠标对其进行操作。
经由过程查找相干材料,总结了一下python用WMI等获得windows体系信息和修正体系的相干设置装备摆设,代码以下(附件中有本代码附件):
#-*-coding:utf-8-*-
importtime
importdatetime
importre
importsubprocess
importsys
importwmi
importos
importConfigParser
import_winreg
importwin32net
importwin32api
importwin32con
importwin32netcon
importwin32security
#DEBUG=True
#DEBUG=False
#LOGFILE=rc:win.log
TIME_FORMAT=r%Y-%m-%d%H:%M:%S
#c=wmi.WMI(privileges=["Admin","Shutdown","Security"])
#实例化wmi类
c=wmi.WMI()
#界说myWmi类并前往实例化对象
classmyWmi(object):
#界说结构器
def__init__(self,wmiclass,info={},name=""):
ifname:
self.obj=wmiclass(Name=name)
else:
self.obj=wmiclass()
self.info=info
returnself.obj
#界说myOs类用于体系信息查询及设置
classmyOs(object):
#界说结构器
def__init__(self,wmiobj=c,info={}):
#创立wmi实例
self.obj=wmiobj.Win32_OperatingSystem()[0]#用于获得盘算机运转情况信息
self.cobj=wmiobj.Win32_ComputerSystem()[0]#用于获得盘算机CPU数目,内存巨细,主板相干信息
self.disk_obj=wmiobj.Win32_DiskDrive()#用于获得硬盘相干信息
self.Partition_obj=wmiobj.Win32_LogicalDisk()#用于获得分区相干信息
self.networkAdapter_obj=wmiobj.Win32_NetworkAdapterConfiguration(IPEnabled=1)#用于设置装备摆设及获得收集衔接相干信息
self.process_obj=wmiobj.Win32_Processor()[0]#用于获得CPU具体信息
self.update_obj=wmiobj.Win32_QuickFixEngineering()#用于获得windows更新补钉相干信息
self.info=info#界说用于寄存设置装备摆设信息的字典
defget_os_info(self):
"""
前往体系相干信息
"""
self.info["os"]=self.obj.Caption#获得体系版本
self.info["version"]=self.obj.CSDVersion#操作体系更新版本
self.info["fullname"]=self.obj.CSName#获得盘算机名
self.info["localtime"]=datetime.datetime.strptime(str(str(self.obj.LocalDateTime).split(.)[0]),%Y%m%d%H%M%S)#获得体系当地时光
self.info["lastboottime"]=datetime.datetime.strptime(str(str(self.obj.LastBootUpTime).split(.)[0]),%Y%m%d%H%M%S)#获得体系前次启动时光
self.info["os_architecture"]=self.obj.OSArchitecture#获得操作体系类型(32bit/64bit)
self.info["mu_languages"]=self.obj.MUILanguages[0]#获得操作体系说话版本
self.info["SerialNumber"]=self.obj.SerialNumber#获得操作体系序列号
self.info["cpu_count"]=self.cobj.NumberOfProcessors#获得cpu数目
self.info["mainboard"]=self.cobj.Manufacturer#获得主板厂商信息
self.info["board_model"]=self.cobj.Model#获得主板型号
self.info["systemtype"]=self.cobj.SystemType#获得主板架构类型
self.info["physical_memory"]=int(self.cobj.TotalPhysicalMemory)/1024/1024#获得内存容量
self.info["cpu_name"]=self.process_obj.Name#获得cpu类型
self.info["clock_speed"]=self.process_obj.MaxClockSpeed#获得操作体系主频
self.info["number_core"]=self.process_obj.NumberOfCores#获得焦点数目
self.info["data_width"]=self.process_obj.DataWidth#获得盘算机的CPU数据宽度
self.info["socket_desigination"]=self.process_obj.SocketDesignation#获得主板cpu接口类型
self.info["l2_cache"]=self.process_obj.L2CacheSize#获得cpu二级缓存巨细
self.info["l3_cache"]=self.process_obj.L3CacheSize#获得cpu三级缓存巨细
returnself.info
#打印补钉更新信息
defupdate_information(self):
output=open(log_path,"a+")
output.write(
)
output.write([Updateinformation]
)
forsinself.update_obj:
output.write(%-10s%-10s%-20s%-10s
%(s.HotFixID,s.InstalledOn,s.Description,s.InstalledBy))
output.write(
)
#打印磁盘信息
defget_diskinfo(self):
foriteminself.disk_obj:
output=open(log_path,"a+")
output.write(
)
output.write([diskinfo]
)
foriteminself.disk_obj:
output.write(%-25sPartition:%-3sSN:%-30s%-3sG
%(item.Caption,str(item.Partitions),item.SerialNumber,str(int(item.Size)/1024/1024/1024)))
#output.write(%-30sPartition:%-5sSN:%-30s%-10sG
%(item.Caption,str(item.Partitions),item.SerialNumber,str((item.Size)/1024/1024/1024)))
output.write(
)
break
#打印磁盘分区信息
defget_partitioninfo(self):
Partition_count=len(self.Partition_obj)
output=open(log_path,"a+")
output.write(
)
output.write([Partitioninfo]
)
output.write(
)
forxinrange(len(self.Partition_obj)):
ifself.Partition_obj[x].DriveType==3:
output.write(DeviceID=%-4sFileSystem=%-5sTotalSize=%-1sGFreeSpace=%-1sG
%(self.Partition_obj[x].DeviceID,self.Partition_obj[x].FileSystem,str(int(self.Partition_obj[x].Size)/1024/1024/1024),str(int(self.Partition_obj[x].FreeSpace)/1024/1024/1024)))
output.write(
)
#打印收集设置装备摆设信息
defget_networkadapter(self):
output=open(log_path,"a+")
output.write(
)
output.write([networkinfo]
)
forinterfaceinself.networkAdapter_obj:
output.write(IPAddress:%-10s
%interface.IPAddress[0])
output.write(NETMask:%-10s
%interface.IPSubnet[0])
output.write(Gateway:%-10s
%interface.DefaultIPGateway)
output.write(PriDNS:%-10s
%str(interface.DNSServerSearchOrder[0]))
output.write(SecDNS:%-10s
%str(interface.DNSServerSearchOrder[1]))
output.write(RealMac:%-10s
%interface.MACAddress)
output.write(
)
break
#强迫关机
defwin32shutdown(self):
self.obj.Win32Shutdown()
#重启操作体系
defreboot(self):
self.obj.Reboot()
#封闭操作体系
defshutdown(self):
self.obj.Shutdown()
#界说network_config类用于收集设相信息查询及设置
classnetwork_config(object):
#界说结构器
def__init__(self,wmiobj=c):
#实例化对象
self.obj=wmiobj.Win32_NetworkAdapterConfiguration
#设置LMHOSTS
defconfig_setup(self):
self.obj.EnableWINS(WINSEnableLMHostsLookup=False)
#设置dns
deftcp_config(self):
interfaces=c.Win32_NetworkAdapterConfiguration(IPEnabled=True)
device_count=len(interfaces)
start_num=0
dns=[202.106.196.115,202.106.0.20]
whileTrue:
forfirst_ifininterfaces:
dns_result=first_if.SetDNSServerSearchOrder(DNSServerSearchOrder=dns)
netbios_result=first_if.SetTcpipNetbios(TcpipNetbiosOptions=2)
start_num+=1
ifstart_num>device_count:
break
returndns_result,netbios_result
#############################
##
#Service#
##
#############################
#定于myService()类用于体系办事检讨及设置
classmyService(object):
"""
controlsystemservice
"""
#界说结构器
def__init__(self,name="",wmiobj=c,**kargs):
self.name=name
kargs={}
args=""
ifself.name:
self.obj=wmiobj.Win32_Service(Name=self.name)[0]#objinthelist
elifkargs:
forkeyinkargs:
args+=key+=+"+kargs[key]+"+,
args=args[:-1]
cmd="wmiobj.Win32_Service("+args+")"
self.obj=eval(cmd)
else:
self.obj=wmiobj.Win32_Service()
defget_service_info(self):
service_list=[]
forserinself.obj:
service_dict={}
service_dict["name"]=ser.Name
service_dict["displayname"]=ser.Caption
service_dict["pid"]=ser.ProcessID
service_dict["stat"]=ser.State
service_dict["startmode"]=ser.StartMode
service_list.append(service_dict)
returnservice_list
#获得体系办事状况
defstatus(self):
returnself.obj.State
#启动办事
defstart(self):
self.obj.StartService()
#停滞办事
defstop(self):
self.obj.StopService()
#封闭黑名单中体系办事
defchange_mode(self,mode):
blacklist_path=sys.path[0]+/data/svr_blacklist.txt
f=open(blacklist_path)
svr_blacklist=f.readlines()
f.close()
forbinsvr_blacklist:
b=b.strip()
forsinself.obj:
ifbins.Name:
"""
Threemodeavailable:Auto,ManualandDisabled
"""
s.ChangeStartMode(mode)
else:
continue
break
#obj.ChangeStartMode(mode)
#删除体系办事
defdelete(self):
print"Youshouldnotdeleteaservice,stopitinstead."
#############################
##
#Process#
##
#############################
#界说myProcess类用于过程检查
classmyProcess(myWmi):
def__init__(self,name=""):
self.name=name
myWmi.__init__(self,c.Win32_Process,name=self.name)
defget_process_info(self):
processlist=[]
forprocessinself.obj:
processlist.append((process.ProcessID,process.Name,process.CreationDate,process.ExecutablePath,process.Caption))
returnprocesslist
defget_process_owner(self):
returnself.obj[0].GetOwner()
defterminate(self):
self.obj[0].Terminate()
#############################
##
#Software#
##
#############################
#界说mySoft类用于装置软件检讨
classmySoft(myWmi):
def__init__(self,name=""):
self.name=name
myWmi.__init__(self,c.Win32_Product,name=self.name)
defget_software(self):
softlist=[]
forsoftinself.obj:
softlist.append((soft.Name,soft.InstallDate))
returnsoftlist
defuninstall(self):
#self.obj[0].Uninstall()
pass
#############################
##
#UserandGroup#
##
#############################
defdump(dict):
forkey,valueindict.items():
printkey,"=",str(value)
#界说myAccount类用于帐号检讨及设置
classmyAccount(myWmi):
#类结构器
def__init__(self,name="",group=""):
self.uname=name
self.gname=group
self.uobj=myWmi.__init__(self,c.Win32_UserAccount,name=self.uname)
self.guobj=myWmi.__init__(self,c.Win32_GroupUser,name=self.gname)
#前往账户列表
defshow_user_list(self):
ulist=[]
foruserinself.uobj:
ulist.append(user.Name)
returnulist
#前往禁用的账户列表
defshow_user_info(self,username):
info=win32net.NetUserGetInfo(None,username,3)
info["disabled"]=user.Disabled#Disabledistruemeanstheaccountisdisabled.
info["status"]=user.Status
returnulist
#前往用户组
defshow_user_in_group(self):
gulist={}
forguinself.guobj:
ifgu.GroupComponent.Namenotingulist:
gulist[gu.GroupComponent.Name]=[gu.PartComponent.Name]
else:
gulist[gu.GroupComponent.Name].append(gu.PartComponent.Name)
returngulist
#前往治理员用户列表
defshow_userlist_admin(self):
uresume=0
whileTrue:
admin_list=[]
users,total,uresume=win32net.NetLocalGroupGetMembers(None,Administrators,0,uresume)
forsidin(u[sid]foruinusers):
username,domain,type=win32security.LookupAccountSid(None,sid)
admin_list.append(username)
returnadmin_list
ifuresume==0:
break
#获得以后用户
defget_current_user(self):
returnwin32api.GetUserName()
#删除用户
defdelete_user(self,username):
win32net.NetUserDel(None,username)
#添加用户
defadd_user(self,name,passwd,flags=win32netcon.UF_NORMAL_ACCOUNT|win32netcon.UF_SCRIPT,privileges=win32netcon.USER_PRIV_ADMIN):
udata={}#userinfodict,canbegottenbywin32net.NetUserGetInfo
udata["name"]=name
udata["password"]=passwd
udata["flags"]=flags
udata["priv"]=privileges
win32net.NetUserAdd(None,1,udata)
#设置用户信息
defmodify_user(self,username,udict,level=2):
win32net.NetUserSetInfo(None,username,level,udict)
#修正用户暗码
defchange_passwd(self,username,oldpass,newpass):
win32net.NetUserChangePassword(None,username,oldpass,newpass)
#重定名账户
defrename_user(self,oldname,newname):
foriteminself.uobj:
ifoldnameinitem.id:
item.Rename(admin)
else:
continue
#############################
##
#Registry#
##
#############################
#界说myRegistry类用于注册表项目检讨及设置
classmyRegistry(object):
"""
#printmyRegistry().get_value(win32con.HKEY_LOCAL_MACHINE,rSAMSAMDomainsAccountUsers,Names)
#myRegistry().add_key(_winreg.HKEY_LOCAL_MACHINE,SOFTWARETJTG)
#printmyRegistry().list_keys(_winreg.HKEY_LOCAL_MACHINE,rSAMSAMDomainsAccountUsersNames)
#myRegistry().add_value(_winreg.HKEY_LOCAL_MACHINE,SOFTWARETJTG,AtionName,TJ7PP)
#myRegistry().delete_value(_winreg.HKEY_LOCAL_MACHINE,SOFTWARETJTG,AtionName)
#myRegistry().delete_key(_winreg.HKEY_LOCAL_MACHINE,SOFTWARETJTG)
#printmyRegistry().get_value(_winreg.HKEY_LOCAL_MACHINE,rSOFTWARETrackerSoftwarepdfxctrl.PdfPrinterPreferences,XCL_PATH)
"""
#界说结构函数
def__init__(self):
#self.obj=wmi.Registry()
self.obj=wmi.WMI(namespace=DEFAULT).StdRegProv
#列出注册表项
deflist_keys(self,root,subkey):
result,names=self.obj.EnumKey(hDefKey=root,sSubKeyName=subkey)
ifresult==2:
print"Nosuchkeys"
returnnames
#前往对应注册表项键值
defget_value(self,root,subkey,valuename,type="string"):
iftype=="string":
result,value=self.obj.GetExpandedStringValue(hDefKey=root,sSubKeyName=subkey,sValueName=valuename)
eliftype=="dword":
result,value=self.obj.GetDWORDValue(hDefKey=root,sSubKeyName=subkey,sValueName=valuename)
else:
result,value=self.obj.GetBinaryValue(hDefKey=root,sSubKeyName=subkey,sValueName=valuename)
returnvalue
#添加注册表项
defadd_key(self,root,subkey):
returnself.obj.CreateKey(hDefKey=root,sSubKeyName=subkey)
#oldvaluecanbeoverwritten
#设置键值
defset_value(self,root,subkey,valuename,value,type):
iftype=="string":
value=self.obj.SetStringValue(hDefKey=root,sSubKeyName=subkey,sValueName=valuename,sValue=value)
else:
value=self.obj.SetDWORDValue(hDefKey=root,sSubKeyName=subkey,sValueName=valuename,uValue=value)
returnvalue
#删除注册表项
defdelete_key(self,root,subkey):
returnself.obj.DeleteKey(root,subkey)
#删除键值
defdelete_value(self,root,subkey,valuename):
returnself.obj.DeleteValue(root,subkey,valuename)
#获得注册表顶用户列表
defget_sys_sid():
reg_user_list=myRegistry().list_keys(_winreg.HKEY_LOCAL_MACHINE,rSAMSAMDomainsAccountUsers)
sid_admin=u000001F4
reg_user_list.remove(sid_admin)
length=len(reg_user_list)
key_list=[]
raw_pattern=re.compile(r^00000)
n=0
whileTrue:
forminreg_user_list:
ifraw_pattern.match(m):
n+=1
ifn<length:
key_list.append(m)
else:
break
break
returnkey_list
#检讨克隆账户
defchk_clone_account():
a=get_sys_sid()
sid_value=myRegistry().get_value(_winreg.HKEY_LOCAL_MACHINE,rSAMSAMDomainsAccountUsers 00001F4,rF,)
#printsid_value
#检讨SID值能否为治理员SID值
foreach_valueina:
path=SAMSAMDomainsAccountUsers+each_value
key_value=myRegistry().get_value(_winreg.HKEY_LOCAL_MACHINE,path,rF,)
ifsid_value==key_value:
#printCloneAccountSIDis%s%each_value
returnTrue
else:
continue
#检讨注册表项中能否有隐蔽帐号
reg_user_list=myRegistry().list_keys(_winreg.HKEY_LOCAL_MACHINE,rSAMSAMDomainsAccountUsersNames)
ulist=myAccount().show_user_list()
foruserinreg_user_list:
ifusernotinulist:
#printCloneAccountis%s%user
returnTrue
#############################
##
#Win_Base_setup#
##
#############################
#界说win_Base类用于体系根本设置装备摆设
classwin_Base():
#实例化
def__init__(self):
#?????ᄅW??????
self.cf=ConfigParser.ConfigParser()
self.cf.read(sys.path[0]+/data/win_reg.ini)
#依据win_reg.ini中读取到的设置装备摆设选项,修正对应注册表项及对应键值
defwin_setup(self):
#???????ᄅW??
section_start=0
section_count=len(self.cf.sections())
section_item=self.cf.sections()
foruserinsection_item:
whileTrue:
foruserinsection_item:
#?????ᄅW???ᄅW??????????
name=self.cf.get(user,"root")
subkey=self.cf.get(user,"sub_key")
valuename=self.cf.get(user,"value_name")
regtype=self.cf.get(user,"reg_type")
#???????ᄀ↑????
ifname==HKEY_LOCAL_MACHINE:
a=_winreg.HKEY_LOCAL_MACHINE
elifname==HKEY_CLASSES_ROOT:
a=_winreg.HKEY_CLASSES_ROOT
elifname==HKEY_CURRENT_USER:
a=_winreg.HKEY_CURRENT_USER
else:
returnname
#??????????
ifregtype=="dword":
value=int(self.cf.get(user,"value"))
else:
value=self.cf.get(user,"value")
#???????ᄀ↑????
myRegistry().add_key(a,subkey)
myRegistry().set_value(a,subkey,valuename,value,regtype)
section_start+=1
ifsection_start==section_count:
break
#############################
##
#Startup#
##
#############################
#界说show_startupcommand类用于体系启动项目检讨
defshow_startupcommand():
startup_list=[]
obj=c.Win32_StartupCommand()
forsinobj:
startup_info={}
startup_info[Name]=s.Name
startup_info[Command]=s.Command
#startup_info[Location]=s.Location
#startup_info[User]=s.User
startup_list.append(startup_info)
#ifs.Commandnotinstartup_list:
#start_value=s.Command++s.Location
#startup_list.append((start_value))
returnstartup_list
startup_list=[]
obj=c.Win32_StartupCommand()
forsinobj:
ifs.Commandnotinstartup_list:
start_value=s.Command++s.Location
startup_list.append((start_value))
returnstartup_list
#############################
##
#AuditLog#
##
#############################
defreg(string):
"""
instanceofWin32_NTLogEvent
{
Category=9;
CategoryString="AccountLogon";
ComputerName="MICROSOF-5524EC";
EventCode=680;
EventIdentifier=680;
EventType=5;
InsertionStrings={"MICROSOFT_AUTHENTICATION_PACKAGE_V1_0","joe","MICROSOF-5524EC","0xC000006A"};
Logfile="Security";
Message="Logonattemptby:MICROSOFT_AUTHENTICATION_PACKAGE_V1_0
Logonaccount:joe
SourceWorkstation:MICROSOF-5524EC
ErrorCode:0xC000006A
";
RecordNumber=16267;
SourceName="Security";
TimeGenerated="20100424000915.000000+480";
TimeWritten="20100424000915.000000+480";
Type="auditfailure";
User="NTAUTHORITYSYSTEM";
};
instanceofWin32_NTLogEvent
{
Category=2;
CategoryString="Logon/Logoff";
ComputerName="MICROSOF-5524EC";
EventCode=529;
EventIdentifier=529;
EventType=5;
InsertionStrings={"joe","MICROSOF-5524EC","2","Advapi","Negotiate","MICROSOF-5524EC"};
Logfile="Security";
Message="LogonFailure:
Reason: Unknownusernameorbadpassword
UserName: joe
Domain: MICROSOF-5524EC
LogonType: 2
LogonProcess: Advapi
AuthenticationPackage: Negotiate
WorkstationName: MICROSOF-5524EC
";
RecordNumber=16251;
SourceName="Security";
TimeGenerated="20100423091037.000000+480";
TimeWritten="20100423091037.000000+480";
Type="auditfailure";
User="NTAUTHORITYSYSTEM";
};
regex=re.compile(r(UserName|Logonaccount):s*w*)
r=re.search(regex,string)
ifr:
returnr.group()
else:
return0
classmyAuditLog():
def__init__(self):
cc=wmi.WMI(privileges=["Security"])
self.obj=cc.Win32_NTLogEvent()
#typellbesuccessorfailure.
defget_history(self,type):
log_type={success:4,failure:5}
s_log=[]
forsinself.obj:
ifs.EventType==log_type[type]:
m=reg(s.Message)
ifm:
s_log.append(s.CategoryString+,+reg(s.Message)+,+s.TimeWritten+,+s.Type)
returns_log"""
#############################
##
#Share#
##
#############################
#界说myShare类用于同享检讨及设置
classmyShare(myWmi):
def__init__(self,name=""):
myWmi.__init__(self,c.Win32_Share)
defshow_share(self):
share_list=[]
forsinself.obj:
item_str=s.Name++s.Path
share_list.append(item_str)
#prints.Name, ,s.Path
returnshare_list
defdelete(self):
forsinself.obj:
s.Delete() |
|