⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 samba3.py

📁 samba最新软件
💻 PY
📖 第 1 页 / 共 2 页
字号:
#!/usr/bin/python# Unix SMB/CIFS implementation.# Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007#   # This program is free software; you can redistribute it and/or modify# it under the terms of the GNU General Public License as published by# the Free Software Foundation; either version 3 of the License, or# (at your option) any later version.#   # This program is distributed in the hope that it will be useful,# but WITHOUT ANY WARRANTY; without even the implied warranty of# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the# GNU General Public License for more details.#   # You should have received a copy of the GNU General Public License# along with this program.  If not, see <http://www.gnu.org/licenses/>.#"""Support for reading Samba 3 data files."""__docformat__ = "restructuredText"REGISTRY_VALUE_PREFIX = "SAMBA_REGVAL"REGISTRY_DB_VERSION = 1import osimport tdbclass TdbDatabase(object):    """Simple Samba 3 TDB database reader."""    def __init__(self, file):        """Open a file.        :param file: Path of the file to open.        """        self.tdb = tdb.Tdb(file, flags=os.O_RDONLY)        self._check_version()    def _check_version(self):        pass    def close(self):        """Close resources associated with this object."""        self.tdb.close()class Registry(TdbDatabase):    """Simple read-only support for reading the Samba3 registry.        :note: This object uses the same syntax for registry key paths as         Samba 3. This particular format uses forward slashes for key path         separators and abbreviations for the predefined key names.         e.g.: HKLM/Software/Bar.    """    def __len__(self):        """Return the number of keys."""        return len(self.keys())    def keys(self):        """Return list with all the keys."""        return [k.rstrip("\x00") for k in self.tdb.keys() if not k.startswith(REGISTRY_VALUE_PREFIX)]    def subkeys(self, key):        """Retrieve the subkeys for the specified key.        :param key: Key path.        :return: list with key names        """        data = self.tdb.get("%s\x00" % key)        if data is None:            return []        import struct        (num, ) = struct.unpack("<L", data[0:4])        keys = data[4:].split("\0")        assert keys[-1] == ""        keys.pop()        assert len(keys) == num        return keys    def values(self, key):        """Return a dictionary with the values set for a specific key.                :param key: Key to retrieve values for.        :return: Dictionary with value names as key, tuple with type and             data as value."""        data = self.tdb.get("%s/%s\x00" % (REGISTRY_VALUE_PREFIX, key))        if data is None:            return {}        ret = {}        import struct        (num, ) = struct.unpack("<L", data[0:4])        data = data[4:]        for i in range(num):            # Value name            (name, data) = data.split("\0", 1)            (type, ) = struct.unpack("<L", data[0:4])            data = data[4:]            (value_len, ) = struct.unpack("<L", data[0:4])            data = data[4:]            ret[name] = (type, data[:value_len])            data = data[value_len:]        return retclass PolicyDatabase(TdbDatabase):    """Samba 3 Account Policy database reader."""    def __init__(self, file):        """Open a policy database                :param file: Path to the file to open.        """        super(PolicyDatabase, self).__init__(file)        self.min_password_length = self.tdb.fetch_uint32("min password length\x00")        self.password_history = self.tdb.fetch_uint32("password history\x00")        self.user_must_logon_to_change_password = self.tdb.fetch_uint32("user must logon to change pasword\x00")        self.maximum_password_age = self.tdb.fetch_uint32("maximum password age\x00")        self.minimum_password_age = self.tdb.fetch_uint32("minimum password age\x00")        self.lockout_duration = self.tdb.fetch_uint32("lockout duration\x00")        self.reset_count_minutes = self.tdb.fetch_uint32("reset count minutes\x00")        self.bad_lockout_minutes = self.tdb.fetch_uint32("bad lockout minutes\x00")        self.disconnect_time = self.tdb.fetch_int32("disconnect time\x00")        self.refuse_machine_password_change = self.tdb.fetch_uint32("refuse machine password change\x00")        # FIXME: Read privileges as wellGROUPDB_DATABASE_VERSION_V1 = 1 # native byte format.GROUPDB_DATABASE_VERSION_V2 = 2 # le format.GROUP_PREFIX = "UNIXGROUP/"# Alias memberships are stored reverse, as memberships. The performance# critical operation is to determine the aliases a SID is member of, not# listing alias members. So we store a list of alias SIDs a SID is member of# hanging of the member as key.MEMBEROF_PREFIX = "MEMBEROF/"class GroupMappingDatabase(TdbDatabase):    """Samba 3 group mapping database reader."""    def _check_version(self):        assert self.tdb.fetch_int32("INFO/version\x00") in (GROUPDB_DATABASE_VERSION_V1, GROUPDB_DATABASE_VERSION_V2)    def groupsids(self):        """Retrieve the SIDs for the groups in this database.        :return: List with sids as strings.        """        for k in self.tdb.keys():            if k.startswith(GROUP_PREFIX):                yield k[len(GROUP_PREFIX):].rstrip("\0")    def get_group(self, sid):        """Retrieve the group mapping information for a particular group.        :param sid: SID of the group        :return: None if the group can not be found, otherwise             a tuple with gid, sid_name_use, the NT name and comment.        """        data = self.tdb.get("%s%s\0" % (GROUP_PREFIX, sid))        if data is None:            return data        import struct        (gid, sid_name_use) = struct.unpack("<lL", data[0:8])        (nt_name, comment, _) = data[8:].split("\0")        return (gid, sid_name_use, nt_name, comment)    def aliases(self):        """Retrieve the aliases in this database."""        for k in self.tdb.keys():            if k.startswith(MEMBEROF_PREFIX):                yield k[len(MEMBEROF_PREFIX):].rstrip("\0")# High water mark keysIDMAP_HWM_GROUP = "GROUP HWM\0"IDMAP_HWM_USER = "USER HWM\0"IDMAP_GROUP_PREFIX = "GID "IDMAP_USER_PREFIX = "UID "# idmap version determines auto-conversionIDMAP_VERSION_V2 = 2class IdmapDatabase(TdbDatabase):    """Samba 3 ID map database reader."""    def _check_version(self):        assert self.tdb.fetch_int32("IDMAP_VERSION\0") == IDMAP_VERSION_V2    def uids(self):        """Retrieve a list of all uids in this database."""        for k in self.tdb.keys():            if k.startswith(IDMAP_USER_PREFIX):                yield int(k[len(IDMAP_USER_PREFIX):].rstrip("\0"))    def gids(self):        """Retrieve a list of all gids in this database."""        for k in self.tdb.keys():            if k.startswith(IDMAP_GROUP_PREFIX):                yield int(k[len(IDMAP_GROUP_PREFIX):].rstrip("\0"))    def get_user_sid(self, uid):        """Retrieve the SID associated with a particular uid.        :param uid: UID to retrieve SID for.        :return: A SID or None if no mapping was found.        """        data = self.tdb.get("%s%d\0" % (IDMAP_USER_PREFIX, uid))        if data is None:            return data        return data.rstrip("\0")    def get_group_sid(self, gid):        data = self.tdb.get("%s%d\0" % (IDMAP_GROUP_PREFIX, gid))        if data is None:            return data        return data.rstrip("\0")    def get_user_hwm(self):        """Obtain the user high-water mark."""        return self.tdb.fetch_uint32(IDMAP_HWM_USER)    def get_group_hwm(self):        """Obtain the group high-water mark."""        return self.tdb.fetch_uint32(IDMAP_HWM_GROUP)class SecretsDatabase(TdbDatabase):    """Samba 3 Secrets database reader."""    def get_auth_password(self):        return self.tdb.get("SECRETS/AUTH_PASSWORD")    def get_auth_domain(self):        return self.tdb.get("SECRETS/AUTH_DOMAIN")    def get_auth_user(self):        return self.tdb.get("SECRETS/AUTH_USER")    def get_domain_guid(self, host):        return self.tdb.get("SECRETS/DOMGUID/%s" % host)    def ldap_dns(self):        for k in self.tdb.keys():            if k.startswith("SECRETS/LDAP_BIND_PW/"):                yield k[len("SECRETS/LDAP_BIND_PW/"):].rstrip("\0")    def domains(self):        """Iterate over domains in this database.        :return: Iterator over the names of domains in this database.        """        for k in self.tdb.keys():            if k.startswith("SECRETS/SID/"):                yield k[len("SECRETS/SID/"):].rstrip("\0")    def get_ldap_bind_pw(self, host):        return self.tdb.get("SECRETS/LDAP_BIND_PW/%s" % host)        def get_afs_keyfile(self, host):        return self.tdb.get("SECRETS/AFS_KEYFILE/%s" % host)    def get_machine_sec_channel_type(self, host):        return self.tdb.fetch_uint32("SECRETS/MACHINE_SEC_CHANNEL_TYPE/%s" % host)    def get_machine_last_change_time(self, host):        return self.tdb.fetch_uint32("SECRETS/MACHINE_LAST_CHANGE_TIME/%s" % host)                def get_machine_password(self, host):        return self.tdb.get("SECRETS/MACHINE_PASSWORD/%s" % host)    def get_machine_acc(self, host):        return self.tdb.get("SECRETS/$MACHINE.ACC/%s" % host)    def get_domtrust_acc(self, host):        return self.tdb.get("SECRETS/$DOMTRUST.ACC/%s" % host)    def trusted_domains(self):        for k in self.tdb.keys():            if k.startswith("SECRETS/$DOMTRUST.ACC/"):                yield k[len("SECRETS/$DOMTRUST.ACC/"):].rstrip("\0")    def get_random_seed(self):        return self.tdb.get("INFO/random_seed")    def get_sid(self, host):        return self.tdb.get("SECRETS/SID/%s" % host.upper())SHARE_DATABASE_VERSION_V1 = 1SHARE_DATABASE_VERSION_V2 = 2class ShareInfoDatabase(TdbDatabase):    """Samba 3 Share Info database reader."""    def _check_version(self):        assert self.tdb.fetch_int32("INFO/version\0") in (SHARE_DATABASE_VERSION_V1, SHARE_DATABASE_VERSION_V2)    def get_secdesc(self, name):        """Obtain the security descriptor on a particular share.                :param name: Name of the share        """        secdesc = self.tdb.get("SECDESC/%s" % name)        # FIXME: Run ndr_pull_security_descriptor        return secdescclass Shares:    """Container for share objects."""    def __init__(self, lp, shareinfo):        self.lp = lp        self.shareinfo = shareinfo    def __len__(self):        """Number of shares."""        return len(self.lp) - 1    def __iter__(self):        """Iterate over the share names."""        return self.lp.__iter__()ACB_DISABLED = 0x00000001ACB_HOMDIRREQ = 0x00000002ACB_PWNOTREQ = 0x00000004ACB_TEMPDUP = 0x00000008ACB_NORMAL = 0x00000010ACB_MNS = 0x00000020ACB_DOMTRUST = 0x00000040ACB_WSTRUST = 0x00000080ACB_SVRTRUST = 0x00000100ACB_PWNOEXP = 0x00000200ACB_AUTOLOCK = 0x00000400ACB_ENC_TXT_PWD_ALLOWED = 0x00000800ACB_SMARTCARD_REQUIRED = 0x00001000ACB_TRUSTED_FOR_DELEGATION = 0x00002000ACB_NOT_DELEGATED = 0x00004000ACB_USE_DES_KEY_ONLY = 0x00008000ACB_DONT_REQUIRE_PREAUTH = 0x00010000ACB_PW_EXPIRED = 0x00020000ACB_NO_AUTH_DATA_REQD = 0x00080000acb_info_mapping = {        'N': ACB_PWNOTREQ,  # 'N'o password.        'D': ACB_DISABLED,  # 'D'isabled.        'H': ACB_HOMDIRREQ, # 'H'omedir required.        'T': ACB_TEMPDUP,   # 'T'emp account.        'U': ACB_NORMAL,    # 'U'ser account (normal).        'M': ACB_MNS,       # 'M'NS logon user account. What is this ?        'W': ACB_WSTRUST,   # 'W'orkstation account.        'S': ACB_SVRTRUST,  # 'S'erver account.         'L': ACB_AUTOLOCK,  # 'L'ocked account.

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -