Beispiel #1
0
 def __init__(self, userName):
   self.domainName, self.userName = UserHelper.parse_user_name(userName)
   if self.domainName:
     self.dcName = win32net.NetGetDCName(None, self.domainName)
   else:
     self.dcName = None
   self._policy = win32security.LsaOpenPolicy(self.dcName,
                                              win32security.POLICY_CREATE_ACCOUNT | win32security.POLICY_LOOKUP_NAMES)
def Main():
    cgiEnv = lib_common.CgiEnv()

    grph = cgiEnv.GetGraph()

    try:
        # TODO: Extends this to have machines as parameters.
        # domainController = win32net.NetGetDCName (None, None)
        # domainController = win32net.NetGetDCName (None, "")
        # ... throws: "Could not find domain controller for this domain."
        # domainController = win32net.NetGetDCName ("127.0.0.1", None)
        # domainController = win32net.NetGetDCName ("192.168.1.83", None)
        # domainController = win32net.NetGetDCName ("192.168.1.83", "")
        # ... throws: "The service has not been started."

        domainController = win32net.NetGetDCName("", "")
    except pywintypes.error:
        exc = sys.exc_info()[1]
        lib_common.ErrorMessageHtml(str(exc))

    domainName = win32net.NetUserModalsGet(domainController, 2)['domain_name']
    sys.stderr.write("Domain name:" + domainName + "\n")
    sys.stderr.write("Domaine Controller:" + domainController + "\n")
    sys.stderr.write("Info=" +
                     str(win32net.NetUserModalsGet(domainController, 2)) +
                     "\n")

    nodeDomain = lib_common.gUriGen.SmbDomainUri(domainName)
    nodeController = lib_common.gUriGen.HostnameUri(domainController)

    grph.add((nodeDomain, pc.property_controller, nodeController))

    sys.stderr.write("About to loop on machine\n")
    cnt = 0

    adsi = win32com.client.Dispatch("ADsNameSpaces")
    nt = adsi.GetObject("", "WinNT:")
    result = nt.OpenDSObject("WinNT://%s" % domainName, "", "", 0)
    result.Filter = ["computer"]

    for machine in result:
        # sys.stderr.write("Machine="+str(machine))
        if machine.Name[0] == '$':
            continue

        # Prefer not to print them because of possible race condition.
        # sys.stderr.write("machineName="+machine.Name+"\n")
        nodeMachine = lib_common.gUriGen.HostnameUri(machine.Name)
        grph.add((nodeDomain, pc.property_domain, nodeMachine))
        cnt += 1
        # TODO: It works fine until 1000 nodes, but after that takes ages to run. What can we do ?????
        # HARDCODE_LIMIT
        if cnt > 1000:
            sys.stderr.write("COULD NOT RUN IT TILL THE END\n")
            break

    cgiEnv.OutCgiRdf()
Beispiel #3
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))
Beispiel #4
0
def getDC(dom=CS_DOMAIN):
        """retourne server de domaine."""
        try:
                #get the server for the domain -- it has to be a primary dc
                dc = str(win32net.NetGetDCName("",dom))
                
        except win32net.error:
                print traceback.format_tb(sys.exc_info()[2]),'\n',sys.exc_type,'\n',sys.exc_value
                dc = "unknown"

        return dc
Beispiel #5
0
def main():
    try:
        domain_controller = win32net.NetGetDCName(None, None)
        domain_name = win32net.NetUserModalsGet(domain_controller,
                                                2)['domain_name']
        adsi = win32com.client.Dispatch("ADsNameSpaces")
        nt = adsi.GetObject("", "WinNT:")
        result = nt.OpenDSObject("WinNT://%s" % domain_name, "", "", 0)
        result.Filter = ["computer"]
        return [machine for machine in result]
    except Exception as e:
        return "Machine enumeration returned error: {}".format(str(e))
Beispiel #6
0
 def _parse_user_name(userName):
   dcName = None
   domainName = None
   domainSepIndex = userName.find('\\')
   if domainSepIndex != -1:
     domainName = userName[0:domainSepIndex]
     userName = userName[domainSepIndex + 1:]
     if domainName == '.' or domainName == win32api.GetComputerName():
       domainName = None
     else:
       dcName = win32net.NetGetDCName(None, domainName)
   return (domainName, dcName, userName)
Beispiel #7
0
def _WinFileOwner(filepath):
    import pywintypes
    import pythoncom
    import win32com.client
    import win32net
    import win32netcon

    OWNERID = (8, 10)  # seems to be 8 on XP, 10 on Win7
    try:
        d = os.path.split(filepath)
        oShell = win32com.client.Dispatch("Shell.Application")
        oFolder = oShell.NameSpace(d[0])
        for oid in OWNERID:
            ownerid = str(oFolder.GetDetailsOf(oFolder.parsename(d[1]), oid))
            if ownerid: break
        try:
            domain, ownerid = ownerid.split('\\')
        except:
            domain, ownerid = None, ownerid.split('\\')[-1]
    except:
        domain, ownerid = None, ''
    #Too slow...
    ##oWMI = win32com.client.GetObject(r"winmgmts:\\.\root\cimv2")
    ##qry = "Select * from Win32_UserAccount where NAME = '%s'" % ownerid
    ##qry = oWMI.ExecQuery(qry)
    ##if qry.count > 0:
    ##for result in qry:
    ##    ownername=str(result.FullName)
    ##    break
    ##else: ownername='No user match'
    #Much quicker...
    try:
        dc = win32net.NetServerEnum(None, 100, win32netcon.SV_TYPE_DOMAIN_CTRL)
        dcname = r'\\' + dc[0][0]['name']
    except:
        try:
            dcname = win32net.NetGetDCName()
        except:
            dcname = None
    try:
        if dcname:
            ownername = win32net.NetUserGetInfo(dcname, ownerid,
                                                2)['full_name']
        else:
            ownername = win32net.NetUserGetInfo(None, ownerid, 2)['full_name']
    except:
        ownername = 'No user match'

    return ownerid, ownername
Beispiel #8
0
def Main():
    cgiEnv = lib_common.CgiEnv()
    machineName = cgiEnv.GetId()
    if lib_util.IsLocalAddress(machineName):
        machineName = None

    if not lib_util.isPlatformWindows:
        lib_common.ErrorMessageHtml(
            "win32 Python library only on Windows platforms")

    try:
        import win32com.client
        import win32net
        import pywintypes
    except ImportError:
        lib_common.ErrorMessageHtml("win32 Python library not installed")

    grph = cgiEnv.GetGraph()

    try:
        # Parameters:
        # Name of remote server on which the function is to execute. If None, local computer.
        # Domain name. If None, name of the domain controller for the primary domain.
        # If machineName="LONW00052257.EURO.NET.INTRA", then it must be truncated to "LONW00052257"
        # Maybe this is a Netbios machine name ?? No idea, just make it work, for the moment.
        if machineName == None:
            machSplit = None
        else:
            machSplit = machineName.split('.')[0]
        WARNING("machineName:%s machSplit:%s", machineName, machSplit)
        domainController = win32net.NetGetDCName(machSplit, None)
    except pywintypes.error:
        exc = sys.exc_info()[1]
        lib_common.ErrorMessageHtml("NetGetDCName:machSplit=%s %s" %
                                    (machSplit, str(exc)))

    # This returns the domain name, for example "EURO".
    domainName = win32net.NetUserModalsGet(domainController, 2)['domain_name']
    DEBUG("Domain name:%s", domainName)
    DEBUG("Domaine Controller:%s", domainController)
    DEBUG("Info=%s", str(win32net.NetUserModalsGet(domainController, 2)))

    nodeDomain = lib_common.gUriGen.SmbDomainUri(domainName)
    nodeController = lib_common.gUriGen.HostnameUri(domainController)

    grph.add((nodeDomain, pc.property_controller, nodeController))

    cnt = 0

    # Sounds like these are the machines in the domain...
    adsi = win32com.client.Dispatch("ADsNameSpaces")
    nt = adsi.GetObject("", "WinNT:")
    result = nt.OpenDSObject("WinNT://%s" % domainName, "", "", 0)
    result.Filter = ["computer"]

    for machine in result:
        # sys.stderr.write("Machine="+str(machine))
        if machine.Name[0] == '$':
            continue

        DEBUG("machineName=%s", machine.Name)
        nodeMachine = lib_common.gUriGen.HostnameUri(machine.Name)
        grph.add((nodeDomain, pc.property_domain, nodeMachine))
        cnt += 1
        # TODO: It works fine until 1000 nodes, but after that takes ages to run. What can we do ?????
        # HARDCODE_LIMIT
        if cnt > 1000:
            WARNING("COULD NOT RUN IT TILL THE END")
            break

    cgiEnv.OutCgiRdf()
Beispiel #9
0
#                 (domain,sys_id)=string.split(domain_id,'\\',1)
#             else:
#                 sys_id=domain_id
#             mask_name=get_mask(mask)
#             Results.append(file+','+sys_id+','+mask_name)
#     Results.sort()
#     return Results
######################################################################################################
#h - help
#r - recursive
#o - output file
#d - directories only

domain = 'HOMEGROUP'

Server = str(win32net.NetGetDCName("", domain))
print '************************ Using domain ', domain

only_dir = 0
D_group = {}
D_except = {}
if len(sys.argv) == 1:
    print sys.argv[0], " file or directory"
    print "-r for recursive mode \n-o for output file (default screen) \n-d for directories only"
    print 'Example:', sys.argv[
        0], '-o a.txt -r c:\\junk  \n ----goes down dir tree in c:\\junk and saves in a.txt'
    sys.exit(0)
else:
    try:
        optlist, args = getopt.getopt(sys.argv[1:], 'dho:r')
    except getopt.error:
Beispiel #10
0
    def __init__(self,
                 userHandle,
                 userSID,
                 userName,
                 domain,
                 forceSidAdd=False):
        """
      Constructs a Windows-specific user perspective used to access the
      event manager.
      @pre userHandle is a valid PyHANDLE object.
      @param userHandle  Handle to the user's authentication.
      @param userSID     The SID for the user represented by this avatar.
      @param userName    The name of the user represented by this avatar.
      @param domain      The domain for the user.
      @param forceSidAdd Causes the given ID to be added to the window
                         station and desktop ACLs even if it is already
                         present. Use with caution!
      """
        assert (userHandle is not None)

        UserPerspective.__init__(self)

        self.mUserHandle = userHandle
        self.mUserSID = userSID
        self.mWinsta = None
        self.mDesktop = None
        self.mAddedHandles = []

        self.mLogger = logging.getLogger('daemon.WindowsAvatar')

        # Save the current window station for later.
        cur_winsta = win32service.GetProcessWindowStation()

        # Open window station winsta0 and make it the window station for this
        # process.
        winsta_flags = win32con.READ_CONTROL | win32con.WRITE_DAC
        new_winsta = win32service.OpenWindowStation("winsta0", False,
                                                    winsta_flags)
        new_winsta.SetProcessWindowStation()

        # Get a handle to the default desktop so that we can change its access
        # control list.
        desktop_flags = win32con.READ_CONTROL         | \
                        win32con.WRITE_DAC            | \
                        win32con.DESKTOP_WRITEOBJECTS | \
                        win32con.DESKTOP_READOBJECTS
        desktop = win32service.OpenDesktop("default", 0, False, desktop_flags)

        # If user_sid is not already among the SIDs who have access to
        # new_winsta, then add it now. It will be removed in logout().
        if forceSidAdd or not windesktop.handleHasSID(new_winsta,
                                                      self.mUserSID):
            windesktop.addUserToWindowStation(new_winsta, self.mUserSID)
            self.mAddedHandles.append(new_winsta)
            self.mLogger.debug("Added SID to new_winsta")

        # If user_sid is not already among the SIDs who have access to desktop,
        # then add it now. It will be removed in logout().
        if forceSidAdd or not windesktop.handleHasSID(desktop, self.mUserSID):
            windesktop.addUserToDesktop(desktop, self.mUserSID)
            self.mAddedHandles.append(desktop)
            self.mLogger.debug("Added SID to desktop")

        cur_winsta.SetProcessWindowStation()

        self.mWinsta = new_winsta
        self.mDesktop = desktop

        #      (username, domain, acct_type) = \
        #         win32security.LookupAccountSid(dc_name, self.mUserSID)
        #      self.mUserName = username
        #      self.mDomain   = domain
        self.mUserName = userName
        self.mDomain = domain

        # Get name of domain controller.
        try:
            dc_name = win32net.NetGetDCName()
        except:
            dc_name = None

        user_info_4 = win32net.NetUserGetInfo(dc_name, self.mUserName, 4)
        profilepath = user_info_4['profile']
        # LoadUserProfile apparently doesn't like an empty string
        if not profilepath:
            profilepath = None

        try:
            # Leave Flags in since 2.3 still chokes on some types of optional
            # keyword args
            self.mUserProfile = win32profile.LoadUserProfile(
                self.mUserHandle, {
                    'UserName': self.mUserName,
                    'Flags': 0,
                    'ProfilePath': profilepath
                })
            self.mLogger.debug("self.mUserProfile = %s" %
                               str(self.mUserProfile))
            self.mLogger.info("Loaded profile %s" % profilepath)
        except pywintypes.error, error:
            self.mLogger.error("Error loading profile: %s" % error)
Beispiel #11
0
def machines_in_default_domain():
    domain_controller = win32net.NetGetDCName(None, None)
    domain_name = win32net.NetUserModalsGet(domain_controller,
                                            2)['domain_name']
    return machines_in_domain(domain_name)
Beispiel #12
0
import active_directory

ini = ConfigParser.ConfigParser()
ini.read("testing_config.ini")


def get_config(section, item, function=ConfigParser.ConfigParser.get):
    if ini.has_option(section, item):
        return function(ini, section, item)
    else:
        return None


try:
    dc = win32net.NetGetDCName().strip("\\")
except win32net.error:
    dc = None
is_inside_domain = bool(dc)

server = get_config("general", "server")
if not server and not dc:
    raise RuntimeError("No server supplied and no DC found")

username = get_config("general", "username")
password = get_config("general", "password")
if server:
    moniker = "LDAP://%s/rootDSE" % server
else:
    moniker = "LDAP://rootDSE"
domain_dn = win32com.client.GetObject(moniker).Get("rootDomainNamingContext")
def my_domain_name():
    domain_controller = win32net.NetGetDCName(None, None)
    domain_name = win32net.NetUserModalsGet(domain_controller,
                                            2)['domain_name']
    return domain_name