#coding:utf-8 ''' __author__ = 'similarface' connection:841196883@qq.com 磁盘操作 ''' import psutil import os import commands import logging import re logger = logging.getLogger('Disk') logger.setLevel(logging.ERROR) ch = logging.StreamHandler() # 定义handler的输出格式formatter formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') ch.setFormatter(formatter) logger.addHandler(ch) from collections import defaultdict class Disk: def getDiskSize(self,part): ''' 获取磁盘分区使用信息 ''' return psutil.disk_usage(part) def getAllCanUseUUID(self): ''' 获取所有可用磁盘的UUID ''' allcanuse=[] canusepart=self.getAllCanUseDiskPart() for part in canusepart: allcanuse.append(self.getUUIDbyPartName(part)) return allcanuse def getMountStatus(self): ''' sdiskpart(device='/dev/sda3', mountpoint='/', fstype='ext4', opts='rw'), ... sdiskpart(device='/dev/sde1', mountpoint='/data3', fstype='ext4', opts='rw')] :return: ''' psutil.disk_partitions() def getMountPartList(self): ''' 获取挂载了的磁盘的NAME :return: ''' partlist=[] try: for item in psutil.disk_partitions(): partlist.append(item.device) return partlist except Exception,e: return partlist def getMountUUID(self): ''' 获取挂载了的磁盘的UUID :return: ''' mountuuidlist=[] for part in self.getMountPartList(): mountuuidlist.append(self.getUUIDbyPartName(part)) return mountuuidlist def getNoMountDisk(self): ''' 获取没有挂载的磁盘 实现方法: 所有的UUID-挂载了的UUID :return: ''' #所有的UUID ALLUUID=self.getAllCanUseUUID() #挂载了的UUID MOUNTUUID=self.getMountUUID() logger.info(ALLUUID) logger.info(MOUNTUUID) return list(set(ALLUUID)-set(MOUNTUUID)) def getPartListNameByUUIDList(self,uuidlist): ''' 根据uuidlist获取partlist :param uuidlist: :return: ''' partlist=[] for uuid in uuidlist: partlist.append(self.getPartNameByUUID(uuid)) return partlist def getPartNameByUUID(self,uuid): ''' 根据UUID 获取partname :param uuid: :return: part name ''' logger.info(uuid) return self.getUUIDPartNameMap()[uuid] def getAllCanUseDiskPart(self): ''' 获取所有可用的磁盘的分区名称 :return: ''' command_str="cat /proc/partitions" #可用分区 partcanuserlist=[] try: status, result=commands.getstatusoutput(command_str) if status==0: rereobj = re.compile('s*') for item in result.split(' '): if not item.startswith("major") and item.strip(): major, minor, blocks,name=rereobj.split(item.strip()) if self.isCanUserPart(major, minor, blocks): partcanuserlist.append('/dev/'+name) return partcanuserlist else: return partcanuserlist except Exception,e: logger.error(e) return partcanuserlist def isCanUserPart(self,major, minor, blocks): ''' 该分区是否可用 算法:设备8 子计数 块大于204800 :param itemlist:['major', 'minor', '#blocks', 'name'] :return:是否可用 ''' try: if int(major)==8 and int(minor)%2==1 and int(blocks)>1: return True else: return False except Exception,e: return False def get(self): psutil.disk_partitions() def getUUIDPartNameMap(self): ''' 获取UUID 和 分区名的对应关系 key:UUID value:partname :return: ''' uuidpartmap={} command_str="ls /dev/disk/by-uuid/ -l|grep -v "total"|awk '{ print $9,"/dev"substr($11,6,5) }'" try: status, result=commands.getstatusoutput(command_str) if status==0: for item in result.split(' '): uuid,parted=item.split(' ') uuidpartmap[uuid]=parted logger.info(uuidpartmap) return uuidpartmap else: logger.error(result) return uuidpartmap except Exception,e: logger.error(e) return uuidpartmap def getUUIDbyPartName(self,part): ''' 根据分区名获取分区的UUID :param part: :return:该分区对应的UUID ''' command_str='blkid '+part try: logger.info(command_str) status, result=commands.getstatusoutput(command_str) if status==0: logger.debug("result:") logger.debug(result) for item in result.strip().split(' '): if item.startswith("UUID"): logger.debug(item) return item.split('=')[1].replace('"','') else: return None except Exception,e: print(e) return None def getPartUUIDNameMap(self): ''' key:Part value:UUID :return:分区-UUID 的字典 ''' uuidpartmap=defaultdict(str) command_str="ls /dev/disk/by-uuid/ -l|grep -v "total"|awk '{ print $9,"/dev"substr($11,6,5) }'" try: status, result=commands.getstatusoutput(command_str) if status==0: for item in result.split(' '): uuid,parted=item.split(' ') uuidpartmap[parted]=uuid return uuidpartmap else: logger.error(result) return uuidpartmap except Exception,e: logger.error(e) return uuidpartmap if __name__=='__main__': a=Disk() #打印没有挂载的磁盘的分区名称 print(a.getPartNameByUUID(a.getNoMountDisk()[0]))