Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python cant see files or folders in C:\Windows\System32\GroupPolicy

I'm running into a problem where python is unable to see folders or files which do exist on the computer. I have already ensured the path has no symbolic links in it and that I have full control on the NTFS file permissions. I have even removed any hidden attributes. Below is the script I am using and its output:

import os
path = 'C:\\Windows\\System32\\GroupPolicy\\Machine'
print path
test = os.path.exists(path)
print test

C:\Windows\System32\GroupPolicy\Machine
False

I am unsure why it is returning False when I have ensured the folder does exist. If I remove "\Machine" from the path, it returns True. I have verified the following command works from a command prompt:

if exist c:\Windows\System32\GroupPolicy\Machine echo found

Any advice on how to get this working in python would be appreciated. Here is the version of python I am using: Python 2.7.6 (default, Nov 10 2013, 19:24:18) [MSC v.1500 32 bit (Intel)] on win32

like image 928
Akblarb Avatar asked Jun 20 '15 01:06

Akblarb


1 Answers

Alright, after some digging, found it is nothing to do with permissions but has to do with File System Redirection. As I am using the x86 version of python on a Windows x64 (using x86 as I am using py2exe), Windows is redirecting any queries on System32 and subdirectories to SysWOW64. This means I was actually querying "C:\Windows\SysWOW64\GroupPolicy\Machine" which did not exist.

To fix this, I found how to disable the File System redirection using the recipe found here: http://code.activestate.com/recipes/578035-disable-file-system-redirector/

Here is my final code which now works to disable the redirection and allows opening and querying of files in System32 on a 64 bit machine.

import ctypes
class disable_file_system_redirection:
    _disable = ctypes.windll.kernel32.Wow64DisableWow64FsRedirection
    _revert = ctypes.windll.kernel32.Wow64RevertWow64FsRedirection
    def __enter__(self):
        self.old_value = ctypes.c_long()
        self.success = self._disable(ctypes.byref(self.old_value))
    def __exit__(self, type, value, traceback):
        if self.success:
            self._revert(self.old_value)


disable_file_system_redirection().__enter__()
import os
path = 'C:\\Windows\\System32\\GroupPolicy\\Machine'
print path
test = os.path.exists(path)
print test
like image 62
Akblarb Avatar answered Oct 16 '22 01:10

Akblarb