利用python开发收集电脑信息

# -*- coding: utf-8 -*-

import socket
from ftplib import FTP
import os, sys, wmi, ctypes, uuid
import win32com.client
import win32con, win32api
from PySide2.QtWidgets import QMainWindow, QApplication, QLineEdit, QPushButton, QMessageBox


class information():
w = wmi.WMI()
list =[]
path= r"C:\Users\Public\Documents\info"
fileName=path+"/"+os.environ['COMPUTERNAME']+".txt" # 文件本地路径
ftpfile="/public/info/"+os.environ['COMPUTERNAME']+".txt" # \\192.168.2.138\public\info

# 获取显示器型号
def get_monitor_list():
list2 = []
reg_root = win32con.HKEY_LOCAL_MACHINE
reg_flags = win32con.KEY_ALL_ACCESS
sub_key = r'SYSTEM\CurrentControlSet\Enum\DISPLAY'
key = win32api.RegOpenKey(reg_root, sub_key, 0, reg_flags)
for j in range(0, win32api.RegQueryInfoKey(key)[0]):
try:
key_name = win32api.RegEnumKey(key, j)
list2.append(key_name)
except:
pass
# 关闭键
win32api.RegCloseKey(key)
return {"Display": list2}

class Inventary(object):
def __init__(self,):
self.inventary()
# self.softlist()
# 获取主机名
hostname = socket.gethostname()
list2 = []
def get_monitor_list(self):
reg_root = win32con.HKEY_LOCAL_MACHINE
reg_flags = win32con.KEY_ALL_ACCESS
sub_key = r'SYSTEM\CurrentControlSet\Enum\DISPLAY'
key = win32api.RegOpenKey(reg_root, sub_key, 0, reg_flags)
for j in range(0, win32api.RegQueryInfoKey(key)[0]):
try:
key_name = win32api.RegEnumKey(key, j)
self.list2.append(key_name)
except:
pass
# 关闭键
win32api.RegCloseKey(key)
# return {"Display": list2}

def get_mac_address(self):
mac = uuid.UUID(int=uuid.getnode()).hex[-12:]
return ":".join([mac[e:e + 2] for e in range(0, 11, 2)])

# 获取想要的资产信息
def inventary(self):
information.list.append("电脑信息")
user = "姓名:%s" %stats.username.text()
information.list.append(user)
strComputer = "."
objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator")
objSWbemServices = objWMIService.ConnectServer(strComputer, "root\cimv2")
colItems = objSWbemServices.ExecQuery("Select * from Win32_Product")
for BIOSs in information.w.Win32_ComputerSystem():
information.list.append("电脑名称: %s" % BIOSs.Caption)
information.list.append("使 用 者: %s" % BIOSs.UserName)
for sys_v in information.w.Win32_OperatingSystem():
information.list.append("系统版本: %s" %sys_v.Caption)
for address in information.w.Win32_NetworkAdapterConfiguration(IPEnabled=True):
information.list.append("IP地址: %s" % address.IPAddress[0])
information.list.append("MAC地址: %s"% self.get_mac_address())
for BIOS in information.w.Win32_BaseBoard():
information.list.append("主板型号: %s" %BIOS.Manufacturer+BIOS.Product)
for processor in information.w.Win32_Processor():
information.list.append("CPU型号: %s" % processor.Name.strip())
for memModule in information.w.Win32_PhysicalMemory():
totalMemSize=int(memModule.Capacity)
information.list.append("内存大小: %.2fGB" %(totalMemSize/1024**3))
for disk in information.w.Win32_DiskDrive(InterfaceType = "IDE"):
# Win32_DiskDrive(InterfaceType = "IDE") 不获取USB移动硬盘
diskSize=int(disk.size)
information.list.append("磁盘大小: %.2fGB" %(diskSize/1024**3))
for xk in information.w.Win32_VideoController():
information.list.append("显卡名称: %s" %xk.name)
self.get_monitor_list()
self.list2 = str(self.list2)
information.list.append("显示器名称: %s" %self.list2)
information.list.append("*****" * 20)
for soft in colItems:
# information.list.append("安装日期: %s" %soft.InstallDate) #获取软件安装日期
information.list.append("软件名称: %s" % soft.Name)


class fileHandling(information):
def __init__(self):
self.file()
self.write()
# 判断(文件夹)路径是否存在
def file(self):
try:
if not os.path.exists(information.path):
# 创建文件夹(文件路径)
os.makedirs(information.path)
else:
# print(information.path)
pass
except Exception as e:
pass
#写入数据
def write(self):
with open(information.fileName,'w+', encoding="utf-8") as f:
for li in information.list:
l=li+"\n"
f.write(l)


#上传、下载FTP文件
class FTPFile(information):
def __init__(self,host,port,username,password):
self.ftp = FTP()
self.host=host #FTP主机IP地址
# print(host)
self.port=port #FTP主机端口号
# print(port)
self.username=username #FTP主机登录名
self.password=password #FTP主机登录密码
self.ftpconnect()
self.uploadfile()

def ftpconnect(self):
self.ftp = FTP()
self.ftp.set_debuglevel(2) #打开调试级别2,显示详细信息
self.ftp.connect(self.host, self.port) #连接
self.ftp.login(self.username, self.password) #登录,如果匿名登录则用空串代替即可
return self.ftp

def downloadfile(self):
bufsize = 1024 #设置缓冲块大小
fp = open(information.fileName,'wb', encoding="utf-8") #以写模式在本地打开文件
self.ftp.retrbinary('RETR ' + information.ftpfile, fp.write, bufsize) #接收服务器上文件并写入本地文件
self.ftp.set_debuglevel(0) #关闭调试
fp.close() #关闭文件

def uploadfile(self):
bufsize = 1024
self.fp = open(information.fileName, 'rb')
self.ftp.storbinary('STOR '+ information.ftpfile , self.fp, bufsize) #上传文件
self.ftp.set_debuglevel(0)
self.fp.close()


class InvenWindow(object):
def __init__(self):
self.window = QMainWindow()
self.window.resize(600, 400)
self.window.move(350, 350)
self.window.setWindowTitle("%s电脑信息"%Inventary.hostname)

self.info = QPushButton(self.window)
self.info.setObjectName("")
self.info.setText(u"提交需要等待3-5秒")
self.info.move(150, 220)
self.info.resize(300, 30)

self.username = QLineEdit(self.window)
self.username.setPlaceholderText("请输入你的名字")
self.username.move(200, 280)
self.username.resize(200, 30)

self.button = QPushButton("提交", self.window)
self.button.move(250, 330)
self.button.clicked.connect(self.mian)

def is_admin(self):
'''
判断是否使用管理员权限,返回值供run判断是否需要提升管理员权限
:return:
:rtype:
'''
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
return False


def mian(self):
infor = information()
inventarys = Inventary()
fileHandlings = fileHandling()
uploadFTP = FTPFile("192.168.3.138", 2121, "soft", "fs2016") # 分别是;ftp服务器地址,端口号,登陆用户,密码
QMessageBox.about(self.window, "状态", '提交成功,请关闭程序')
self.window.close()

def is_admin():
'''
判断是否使用管理员权限,返回值供run判断是否需要提升管理员权限
:return:
:rtype:
'''
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
return False

def run():
if is_admin():
pass
else: # 提升管理员权限再执行。
if sys.version_info[0] == 3:
ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, __file__, None, 1)
else:#in python2.x
ctypes.windll.shell32.ShellExecuteW(None, u"runas", unicode(sys.executable), unicode(__file__), None, 1)

if __name__ == "__main__":
run()
app = QApplication([])
stats = InvenWindow()
stats.window.show()
app.exec_()
posted @ 2020-11-30 15:18  Feng_fu  阅读(463)  评论(0编辑  收藏  举报