首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >标识Linux passwd文件

标识Linux passwd文件
EN

Stack Overflow用户
提问于 2020-04-22 12:01:45
回答 1查看 497关注 0票数 0

我需要帮助编写一个函数(最好是python),以确定一个文件是/etc/passwd还是etc/影子。到目前为止,我已经尝试使用print(pw.getpwall()),但是它从os env读取文件。我需要一个接受输入的库,它可以判断一个文件是否是passwd/影子文件。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-04-22 16:09:33

passwd文件格式和阴影文件格式不同。

您可以编写一个简短的函数或类。第一次迭代将是:

  1. 查找用户,几乎100%的事实是,根是第一次输入
  2. 检查第2列、第6列和第7列(分隔符是符号)

H 19如果第2列是E 110xE 211>,第6列是E 112/根<代码>E 213,第7列是E 114/code>/bin/*shE 215,那么它几乎是一个密码文件,在100%H 216H 117/code>如果第二个是盐类和散列(格式:E 118代码$$6),并且代码是第7位,并且代码是<<100%<

<代码><<<><><><220>

当然,可能会出现以下问题:

  • Linux配置为不使用阴影文件。在本例中,pasword文件第2列包含password
  • Linux,配置为不使用salt (我猜是否可能)

请查看手册:man 5 passwd和man 5 shadow

编辑,2020-04-24:这是我更正的pwd.py:

代码语言:javascript
复制
#!/usr/bin/env python3

import os
import sys

passwd_file=('./passwd')

# path conversion handlers
def __nullpathconv(path):
    return path

def __unixpathconv(path):
    return path

# decide what field separator we can try to use - Unix standard, with
# the platform's path separator as an option.  No special field conversion
# handler is required when using the platform's path separator as field
# separator, but are required for the home directory and shell fields when
# using the standard Unix (":") field separator.
__field_sep = {':': __unixpathconv}
if os.pathsep:
    if os.pathsep != ':':
        __field_sep[os.pathsep] = __nullpathconv

# helper routine to identify which separator character is in use
def __get_field_sep(record):
    fs = None
    for c in list(__field_sep.keys()):
        # there should be 6 delimiter characters (for 7 fields)
        if record.count(c) == 6:
            fs = c
            break
    if fs:
        return fs
    else:
        raise KeyError

# class to match the new record field name accessors.
# the resulting object is intended to behave like a read-only tuple,
# with each member also accessible by a field name.
class Passwd:
    def __init__(self, name, passwd, uid, gid, gecos, dir, shell):
        self.__dict__['pw_name'] = name
        self.__dict__['pw_passwd'] = passwd
        self.__dict__['pw_uid'] = uid
        self.__dict__['pw_gid'] = gid
        self.__dict__['pw_gecos'] = gecos
        self.__dict__['pw_dir'] = dir
        self.__dict__['pw_shell'] = shell
        self.__dict__['_record'] = (self.pw_name, self.pw_passwd,
                                    self.pw_uid, self.pw_gid,
                                    self.pw_gecos, self.pw_dir,
                                    self.pw_shell)

    def __len__(self):
        return 7

    def __getitem__(self, key):
        return self._record[key]

    def __setattr__(self, name, value):
        raise AttributeError('attribute read-only: %s' % name)

    def __repr__(self):
        return str(self._record)

    def __cmp__(self, other):
        this = str(self._record)
        if this == other:
            return 0
        elif this < other:
            return -1
        else:
            return 1

# read the whole file, parsing each entry into tuple form
# with dictionaries to speed recall by UID or passwd name
def __read_passwd_file():
    if passwd_file:
        passwd = open(passwd_file, 'r')
    else:
        raise KeyError
    uidx = {}
    namx = {}
    sep = None
    while 1:
        entry = passwd.readline().strip()
        if len(entry) > 6:
            if sep is None:
                sep = __get_field_sep(entry)
            fields = entry.split(sep)
            for i in (2, 3):
                fields[i] = int(fields[i])
            for i in (5, 6):
                fields[i] = __field_sep[sep](fields[i])
            record = Passwd(*fields)
            if fields[2] not in uidx:
                uidx[fields[2]] = record
            if fields[0] not in namx:
                namx[fields[0]] = record
        elif len(entry) > 0:
            pass                         # skip empty or malformed records
        else:
            break
    passwd.close()
    if len(uidx) == 0:
        raise KeyError
    return (uidx, namx)

# return the passwd database entry by UID
def getpwuid(uid):
    u, n = __read_passwd_file()
    return u[uid]

# return the passwd database entry by passwd name
def getpwnam(name):
    u, n = __read_passwd_file()
    return n[name]

# return all the passwd database entries
def getpwall():
    u, n = __read_passwd_file()
    return list(n.values())

# test harness
if __name__ == '__main__':
    print(getpwall())
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61364646

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档