簡體   English   中英

如何使用python在linux中創建用戶

[英]How to create a user in linux using python

如何使用 Python 在 Linux 中創建用戶? 我的意思是,我知道 subprocess 模塊並考慮過調用“adduser”並一次傳遞所有參數,但是“adduser”命令會詢問一些問題,例如密碼、全名、電話等。 我將如何使用子流程回答這個問題? 我在這個問題中看到了名為 pexpect 的模塊: Can I use Python as a Bash replacement? . 有沒有其他標准模塊?

使用useradd ,它不問任何問題,但接受許多命令行選項。

在 Ubuntu 上,你可以使用python-libuser

import os
import crypt

password ="p@ssw0rd" 
encPass = crypt.crypt(password,"22")
os.system("useradd -p "+encPass+" johnsmith")

您可以只使用內置二進制文件,因此只需通過 subprocess 模塊調用 useradd 或其他東西,但是我不知道是否有任何其他模塊可以連接到 Linux 以提供此類功能。

def createUser(name,username,password):
    encPass = crypt.crypt(password,"22")   
    return  os.system("useradd -p "+encPass+ " -s "+ "/bin/bash "+ "-d "+ "/home/" + username+ " -m "+ " -c \""+ name+"\" " + username)

這是shell為假的解決方案。

#!/bin/env/python

import subprocess
import traceback
import sys


def user_add(username, user_dir=None):
    if user_dir:
        cmd = ["sudo", "useradd", "-d", user_dir, "-m", username]
    else:
        cmd = ["sudo", "useradd", username]

    p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    output, error = p.communicate()
    output = output.strip().decode("utf-8")
    error = error.decode("utf-8")
    if p.returncode != 0:
        print(f"E: {error}")
        raise
    return output


try:
    username = "user"
    output = user_add(username)
    print(F"Success. {username} is added")
except:
    traceback.print_exc()
    sys.exit(1)


暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM