KeyError:'getpwnam():找不到名称:user1'

时间:2018-09-13 18:58:54

标签: python-3.6

我正在创建一个简单的脚本来检查用户是否存在于linux系统上(如果不存在),然后创建一个脚本并获取其“ uid / gid”以进行进一步处理。问题是'pwd.getpwnam('user')。pw_uid'正在生成我无法理解的错误。如果您查看跟踪,则已经创建了该用户,那么为什么此命令找不到新创建的用户,对此可能有什么解决办法?这是脚本:

#!/usr/bin/env python3

import sys
import pwd
import grp
import subprocess


def _init():
    _username = "user1"
    return _username


def _checkusername():
    try:
        pwd.getpwnam(_init())

    except KeyError:
        _adduser()

    else:
        print("User already exists, exiting...")
        sys.exit(1)


def _adduser():
    subprocess.Popen(['useradd', '-m', _init()])
    print("User created.")
    _getuid()


def _getuid():
    uid = pwd.getpwnam(_init()).pw_uid
    gid = grp.getgrnam(_init()).gr_gid
    print(uid, gid)


_init()
_checkusername()

这是运行脚本时得到的跟踪:

# python3 test.py
User created.
Traceback (most recent call last):
  File "test.py", line 20, in _checkusername
    pwd.getpwnam(_init())
KeyError: 'getpwnam(): name not found: user1'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "test.py", line 43, in <module>
    _checkusername()
  File "test.py", line 23, in _checkusername
    _adduser()
  File "test.py", line 33, in _adduser
    _getuid()
  File "test.py", line 37, in _getuid
    uid = pwd.getpwnam(_init()).pw_uid
KeyError: 'getpwnam(): name not found: user1'

谢谢!

0 个答案:

没有答案