def is_nt_ssd(path): import win32file flag = False path = _fullpath(path) drive = splitdrive(path)[0].upper() drivetype = win32file.GetDriveType(drive) if drivetype == win32file.DRIVE_RAMDISK: flag = True elif drivetype in (win32file.DRIVE_FIXED, win32file.DRIVE_REMOVABLE): import wmi c = wmi.WMI() phy_to_part = 'Win32_DiskDriveToDiskPartition' log_to_part = 'Win32_LogicalDiskToPartition' index = dict((log_disk.Caption, phy_disk.Index) for phy_disk in c.Win32_DiskDrive() for partition in phy_disk.associators(phy_to_part) for log_disk in partition.associators(log_to_part)) c = wmi.WMI(moniker='//./ROOT/Microsoft/Windows/Storage') flag = bool( c.MSFT_PhysicalDisk(DeviceId=str(index[drive]), MediaType=4)) return flag
def get_read_drive(): # 현재 인식된 드라이브의 목록을 문자열로 반환하는 메소드 drive = wa.GetLogicalDriveStrings() # 드라이브의 목록을 '\000'으로 나눠서 'list'로 변환한다. drive = drive.split('\000')[:-1] drive_list = [] # USB의 경로를 담아서 반환할 변수 rdrive = [] r_count = 0 # 이동식 드라이브를 확인하는 반복문 for drv in drive: # 만약 drive list 에서 이동식 드라이브가 있다면 # drive_list 에다 추가한다. # 그럼 이동식 드라이브의 경로가 drive_list 에 추가되겠지? if wf.GetDriveType(drv) == wf.DRIVE_REMOVABLE: drive_list.append(drv) # 이동식 드라이브를 찾으면 +1 을 해준다. r_count += 1 # 이동식 드라이브를 찾았을 때 +해준 r_count 를 이용해서 # 찾은 이동식 드라이브의 경로를 rdrive 에 추가한다. # 이 부분의 코드가 블로그에 나와있는 예제랑 다르게 작성됨 for drv in range(r_count): if os.path.getsize(drive_list[drv]) >= 0: rdrive.append(drive_list[drv]) return rdrive, r_count
def main(): print('wdh v0.1\nFinding disc drives...') discs = [] drive_strings = win32api.GetLogicalDriveStrings() for d in drive_strings.split('\x00')[:-1]: if win32file.GetDriveType(d) == win32file.DRIVE_CDROM: discs.append(d) if len(discs) < 1: print('Error! No discs found.') return 1 disc_path, _ = pick.pick(discs, 'Select disc to hash:', indicator='->') sectors = psutil.disk_usage(disc_path).total // BD_SECTOR_SIZE bar = progressbar.ProgressBar(max_value=sectors) md5sum = hashlib.md5() sha1sum = hashlib.sha1() full_disc_path = '\\\\.\\{D}:'.format(D=disc_path[0]) disc_descriptor = os.open(full_disc_path, os.O_RDONLY | os.O_BINARY) with os.fdopen(disc_descriptor, 'rb+') as disc: print('Hashing {d} (go grab some coffee)...'.format(d=disc_path)) for counter, _ in enumerate(range(sectors)): raw_data = disc.read(BD_SECTOR_SIZE) md5sum.update(raw_data) sha1sum.update(raw_data) bar.update(counter) print('\nmd5: {md5}\nsha1: {sha1}'.format(md5=md5sum.hexdigest(), sha1=sha1sum.hexdigest())) return 0
def _maybepossible(d,allowfixed=0): drive=chr(ord('A')+d) # here if the drive is at least there drname='%c:\\' % drive[0] t=win32file.GetDriveType(drname) if t == win32file.DRIVE_REMOVABLE: try: fr,tot,totfr=win32file.GetDiskFreeSpaceEx(drname) if tot > 30000000 and tot < 66000000000: return 1 except: return 0 else: if 1: if t == win32file.DRIVE_FIXED or t == win32file.DRIVE_REMOVABLE: # see if it is already a remote drive ans,lns=_checksdhdr(drive) if ans == 0: return 1 # must determine size, etc. try: fr,tot,totfr=win32file.GetDiskFreeSpaceEx(drname) except: tot=0 if tot > 30000000 and tot < 66000000000: if _regcheck(drive) or allowfixed: return 1 return 0
def get_drives(): # Get all drives except those that are network drives drives = win32api.GetLogicalDriveStrings().split('\x00')[:-1] return [ d for d in drives if not win32file.GetDriveType(d) == win32file.DRIVE_REMOTE ]
def main(argv): #------------------------------------------------------------------------------- """ usage: drives.py shows the available drives on the system and (free space/total space) """ args, opts = oss.gopt(argv[1:], [], [], main.__doc__) drives = w32.GetLogicalDrives() for i in range(26): if drives & (1 << i): dl = chr(i + ord('A')) rootpath = dl + ':\\' tp = w32.GetDriveType(rootpath) print(" %s:" % dl, S[tp], end='') try: f, t, d = w32.GetDiskFreeSpaceEx(rootpath) if tp == 4: print(" (%s/%s)" % (util.CvtGigMegKBytes(f), util.CvtGigMegKBytes(t)), end='') print(" [%s]" % wnet.WNetGetUniversalName(rootpath, 1)) else: print(" (%s/%s)" % (util.CvtGigMegKBytes(f), util.CvtGigMegKBytes(t))) except: print(" -- not ready") oss.exit(0)
def Init(self): self.Bind(wx.EVT_BUTTON, self.BtnSearchClick, self.btnSearch) self.Bind(wx.EVT_BUTTON, self.BtnDownloadClick, self.btnDownload) self.Bind(wx.EVT_BUTTON, self.BtnPathClick, self.btnPath) self.Bind(wx.EVT_CLOSE, self.OnClose) # 設定快速鍵 entries = [wx.AcceleratorEntry() for i in range(3)] entries[0].Set(wx.ACCEL_ALT, ord('S'), self.btnSearch.GetId()) entries[1].Set(wx.ACCEL_ALT, ord('D'), self.btnDownload.GetId()) entries[2].Set(wx.ACCEL_ALT, ord('P'), self.btnPath.GetId()) table = wx.AcceleratorTable(entries) self.SetAcceleratorTable(table) # 載入 chromedriver opt = Options() # opt.add_argument('--headless') opt.add_argument('--disable-gpu') # opt.add_experimental_option('excludeSwitches', ['enable-loggin']) self.web = webdriver.Chrome('chromedriver.exe', options=opt) # 選取硬碟 disk = [] for i in win32api.GetLogicalDriveStrings().split('\000'): if win32file.GetDriveType(i) == 3: disk.append(i[:-2]) # print(disk) if not os.path.isdir(self.lblPath.GetLabelText()): os.mkdir(self.lblPath.GetLabelText()) self.lblPath.SetLabelText('{0}:\mp3_tmp'.format(disk[len(disk) - 1]))
def detect_usb(self): # TODO - Should this return if nothing is in the whitelist? # Feels like it should be done elsewhere. if not self.config['windows']['usb_id_whitelist']: log.warning("No USB devices whitelisted, skipping detection...") return ids = [] for each in win32api.GetLogicalDriveStrings().split('\\\x00'): if win32file.GetDriveType(each) == win32file.DRIVE_REMOVABLE: decimal_id = win32api.GetVolumeInformation(each[1]) hex_id = '%X' % (0x100000000 + decimal_id) ids.append(hex_id) log.debug('USB:', ', '.join(ids) if ids else 'none detected') for each_device in ids: if each_device not in self.config['windows']['usb_id_whitelist']: self.kill_the_system('USB Allowed Whitelist: {0}'.format(each_device)) else: if self.config['windows']['usb_id_whitelist'][each_device] != ids.count(each_device): self.kill_the_system('USB Duplicate Device: {0}'.format(each_device)) for device in self.config['windows']['usb_connected_whitelist']: if device not in ids: self.kill_the_system('USB Connected Whitelist: {0}'.format(device)) else: if self.config['windows']['usb_connected_whitelist'][each_device] != ids.count(each_device): self.kill_the_system('USB Whitelist Duplicate Device: {0}'.format(each_device))
def GetDriveObject(index): """ドライブ情報を調べて、browsableObjectsで返す。Aドライブが0、Zドライブが25。""" letter = chr(index + 65) path = letter + ":\\" type = win32file.GetDriveType(path) f = -1 t = -1 n = "" try: volumeInfo = win32api.GetVolumeInformation(path) n = volumeInfo[0] freeSpace = win32api.GetDiskFreeSpaceEx(path) f = freeSpace[0] t = freeSpace[1] except pywintypes.error as err: pass # エラーは無視 d = browsableObjects.Drive() if type != win32file.DRIVE_REMOTE or t != -1: ret, shfileinfo = shell.SHGetFileInfo(letter + ":\\", 0, shellcon.SHGFI_ICON) d.Initialize(letter, f, t, type, n, shfileinfo[0]) else: d.Initialize(letter, f, t, type, n, -1) return d
def get_removable_drives(): drive_list = win32api.GetLogicalDriveStrings() drive_list = drive_list.split('\x00')[0:-1] for letter in drive_list: if win32file.GetDriveType(letter) == win32file.DRIVE_REMOVABLE: list_removable_drives.append(letter) return list_removable_drives
def count_any_files(drive, extension): '''Count number of files of given extension available in your drive''' counter = 0 exclude = ['$RECYCLE.BIN', '$Recycle.Bin', '$SysReset', 'Config.Msi', 'Documents and Settings', 'ESD', 'hiberfil.sys', 'Intel', 'MSOCache', 'OneDriveTemp', 'pagefile.sys', 'PerfLogs', 'Program Files', 'Program Files (x86)', 'ProgramData', 'Python27', 'Recovery', 'swapfile.sys', 'System Volume Information', 'Windows', 'Public', '.idlerc', 'AppData', 'MicrosoftEdgeBackups', 'All Users'] # These directories is to be excluded. Add if you want other too drive_types = (win32con.DRIVE_REMOVABLE,) # Removable disk type try: if win32file.GetDriveType(drive) in drive_types: # Check if the the listed drive is removeable print('{} is removeable drive. Do not remove it until this process completes'.format(drive)) for dirs, dirn, files in os.walk(drive): # Walking through all directories and files of a given drive for di in dirn: if di in exclude: dirn.remove(di) # Removing directory if they are in exclude list for f in files: if f.endswith(extension): # Checking if the obtained file's name end with given extension counter += 1 print('{}{}\n{}{}'.format('Drive'.ljust(15), 'Number of {} files'.format(extension).rjust(15), drive.rjust(4), str(counter).rjust(23))) except WindowsError as err: if err.strerror == 'The device is not ready': print('{} is not ready to use'.format(drive)) if err.strerror == 'This drive is locked by BitLocker Drive Encryption. You must unlock this drive from Control Panel': print('{} is locked by BitLocker Drive Encryption. You must unlock this drive from Control Panel'.format(drive))
def get_drive_letters_and_types(): import os import win32api import win32file # os.system("cls") drive_types = { win32file.DRIVE_UNKNOWN: "Unknown\nDrive type can't be determined.", win32file.DRIVE_REMOVABLE: "Removable\nDrive has removable media. This includes all floppy drives and many other varieties of storage devices.", win32file.DRIVE_FIXED: "Fixed\nDrive has fixed (nonremovable) media. This includes all hard drives, including hard drives that are removable.", win32file.DRIVE_REMOTE: "Remote\nNetwork drives. This includes drives shared anywhere on a network.", win32file.DRIVE_CDROM: "CDROM\nDrive is a CD-ROM. No distinction is made between read-only and read/write CD-ROM drives.", win32file.DRIVE_RAMDISK: "RAMDisk\nDrive is a block of random access memory (RAM) on the local computer that behaves like a disk drive.", win32file.DRIVE_NO_ROOT_DIR: "The root directory does not exist." } drives = win32api.GetLogicalDriveStrings().split('\x00')[:-1] r = [] for device in drives: type = win32file.GetDriveType(device) r.append([ device, type, drive_types[type], ]) # print("Drive: %s" % device) # print(drive_types[type]) # print("-"*72) return r
def amovible(key): ''' **FR** Test si le périphérique passé en paramètre est amovible **EN** Test if device in parameter is removable ''' return win32file.GetDriveType(key) == win32file.DRIVE_REMOVABLE
def getRemovableDrives(): drives = [i for i in win32api.GetLogicalDriveStrings().split("\x00") if i] rdrives = [ d for d in drives if win32file.GetDriveType(d) == win32con.DRIVE_REMOVABLE ] rdrives = map(lambda x: x.replace(":\\", ""), rdrives) return list(rdrives)
def getDriveLetters(self): driveletters = [] for drive in string.ascii_uppercase: if win32file.GetDriveType(drive + ":") in [win32file.DRIVE_FIXED, win32file.DRIVE_REMOTE, win32file.DRIVE_RAMDISK, win32file.DRIVE_REMOVABLE]: driveletters.append(drive + ":\\") return driveletters
def test1(): drive = [] for i in range(25): if win32file.GetDriveType(drive_all[i]) == 2: break drive.append(drive_all[i]) print(drive_all[i])
def enumerate_drives(self): drives = [] for i in string.ascii_lowercase: t = "%s:\\" % i if win32file.GetDriveType(t) == win32file.DRIVE_FIXED: drives.extend(t[0]) self.drive_str = ', '.join(a.upper() for a in drives)
def getDriveLetters(self): driveletters = [] for drive in string.ascii_uppercase: if win32file.GetDriveType(drive + ":") == win32file.DRIVE_FIXED: driveletters.append(drive + ":") return driveletters
def getDefaultIndexableRootDirectories(): directories = [] drives = win32api.GetLogicalDriveStrings().split("\x00") for drive in drives: if win32file.GetDriveType(drive) == win32file.DRIVE_FIXED: directories.append(drive) return directories
def is_partition_supported(folder): if folder[-1] != os.path.sep: folder = folder + os.path.sep if win32file.GetDriveType(folder) != win32file.DRIVE_FIXED: return False volume = win32file.GetVolumePathName(folder) t = win32api.GetVolumeInformation(volume) return t[-1] == 'NTFS'
def get_removable_drives(): """Returns a list containing letters from removable drives""" drive_list = win32api.GetLogicalDriveStrings() drive_list = drive_list.split("\x00")[0:-1] # the last element is "" list_removable_drives = [] for letter in drive_list: if win32file.GetDriveType(letter) == win32file.DRIVE_REMOVABLE: list_removable_drives.append(letter) return list_removable_drives
def get_ramdrive_by_label(): ramdisk_drives = [] driver_list_str = win32api.GetLogicalDriveStrings() for driver in driver_list_str.split('\x00'): # 2 is removable driver, im ramdisk is 2 if win32file.GetDriveType(driver) == 2 and win32api.GetVolumeInformation(driver+'\\')[0] == 'RamDisk': ramdisk_drives.append(driver[0:2]) return ramdisk_drives
def get_drive(self): drive = wa.GetLogicalDriveStrings() drive = drive.split('\000')[:-1] usb_drive = [] for drv in drive: if wf.GetDriveType(drv) == wf.DRIVE_REMOVABLE: usb_drive.append(drv) return usb_drive
def is_on_fixed_drive(path): if is_unc_path(path): # All UNC paths (\\host\mount) are considered not-fixed return False drive, remain = os.path.splitdrive(path) if drive: return win32file.GetDriveType(drive) == win32file.DRIVE_FIXED else: return False
def get_drives_list(self): drives = [ i for i in win32api.GetLogicalDriveStrings().split('\x00') if i ] rdrives = [ d for d in drives if win32file.GetDriveType(d) == win32con.DRIVE_REMOVABLE ] return rdrives
def test_usb(type, fmt=False): if fmt: os.system('adb reboot') os.system('adb wait-for-device') while os.popen('adb shell getprop sys.boot_completed').readline( ).strip() != '1': time.sleep(3) os.popen('adb push \"{0}\" /data/local/tmp'.format( os.path.join(workdir, 'ramdisk.sh'))).readlines() os.popen('adb shell sh /data/local/tmp/ramdisk.sh').readlines() os.system('adb shell setprop sys.usb.config {0},adb'.format(type)) os.system('adb wait-for-device') drive = None loop = 1 read = 0 write = 0 while not drive: if loop > 20: break r = win32file.GetLogicalDrives() for d in range(26): if r >> d & 1 and win32file.GetDriveType(string.ascii_letters[d] + ':\\') == 2: drive = string.ascii_letters[d] break time.sleep(3) loop += 1 if drive: if fmt: os.system('echo y | format {0}: /fs:fat32 /q'.format(drive)) file1 = os.path.join(workdir, 'test.zip') file2 = os.path.join(drive + ':' + os.sep, 'test.zip') if os.path.exists(file2): os.remove(file2) st = time.time() shell.SHFileOperation( (0, shellcon.FO_COPY, file1, file2, 0, None, None)) write = round( os.path.getsize(file1) / 1048576.0 / (time.time() - st), 2) file3 = os.path.join(workdir, 'tmp.zip') if os.path.exists(file3): os.remove(file3) st = time.time() shell.SHFileOperation( (0, shellcon.FO_COPY, file2, file3, 0, None, None)) read = round( os.path.getsize(file2) / 1048576.0 / (time.time() - st), 2) os.remove(file2) os.remove(file3) os.popen('adb shell rm /data/local/tmp/ramdisk.sh').readlines() return (read, write)
def get_fixed_drives(): """Yield each fixed drive""" for drive in win32api.GetLogicalDriveStrings().split('\x00'): if win32file.GetDriveType(drive) == win32file.DRIVE_FIXED: # Microsoft Office 2010 Starter creates a virtual drive that # looks much like a fixed disk but isdir() returns false # and free_space() returns access denied. # https://bugs.launchpad.net/bleachbit/+bug/1474848 if os.path.isdir(drive): yield unicode(drive)
def get_windows_drives(): import win32api import win32file drives = win32api.GetLogicalDriveStrings() drives = drives.split('\000')[:-1] phys = [] for d in drives: if win32file.GetDriveType(d) == win32file.DRIVE_FIXED: phys.append(d) return phys
def getDrives(self): '''Assign all available cd drives to self.drives. If CdRom.drive is not already set the first drive returned becomes the default. ''' letters = [l.upper() + ':' for l in 'abcdefghijklmnopqrstuvwxyz'] for drive in letters: if win32file.GetDriveType(drive) == 5: self.drives.append(drive) if not self.drive: self.drive = self.drives[0]
def updateShares(avatar): # Get name of domain controller. try: dc_name = win32net.NetGetDCName() except: dc_name = None saved_username = avatar.mUserName # Get user sid to lookup registry values. user_sid = win32security.GetTokenInformation(avatar.mUserHandle, ntsecuritycon.TokenUser)[0] user_sid_str = win32security.ConvertSidToStringSid(user_sid) # Act as the user so that we can update session shares. win32security.ImpersonateLoggedOnUser(avatar.mUserHandle) try: # Get username user_name = win32api.GetUserName() if user_name != saved_username: raise Exception("Impersonation failed due to user name mismatch ('%s' is not '%s')" % \ (user_name, saved_username)) gLogger.debug("User: '******'" % user_name) gLogger.debug("Domain Controller: '%s'" % dc_name) gLogger.info("\n=== Disconnect from all network drives ===") # Disconnect from all network drives. drive_list_str = win32api.GetLogicalDriveStrings().rstrip('\x00') drive_list = drive_list_str.split('\x00') for drive in drive_list: if win32file.DRIVE_REMOTE == win32file.GetDriveType(drive): disconnectNetworkDrive(drive) gLogger.info("\n=== Map network drives ===") # Map the user's home directory. user_info = win32net.NetUserGetInfo(dc_name, user_name, 4) try: if user_info['home_dir_drive'] != '' and user_info[ 'home_dir'] != '': mapNetworkDrive(user_info['home_dir_drive'], user_info['home_dir']) except KeyError, ke: gLogger.error(ke) # Map the user's persistent network drives. try: user_reg = maestro.util.registry.RegistryDict( win32con.HKEY_USERS, str(user_sid_str)) for k, v in user_reg['Network'].iteritems(): drive = k + ':' mapNetworkDrive(drive, v['RemotePath']) except KeyError, ke: gLogger.warning("Unknown registry key %s" % str(ke))