ユーザーの対話なしでパスワードでユーザーを作成する最善の方法は何ですか? (ユーザーパスワード要求)(Ubuntu)

ユーザーの対話なしでパスワードでユーザーを作成する最善の方法は何ですか? (ユーザーパスワード要求)(Ubuntu)

追放ファイルのユーザー名とパスワードを使用してユーザーアカウントを作成するPythonスクリプトを作成しています。ただし、パスワードでユーザーを作成できる1行のコマンドは見つかりません。 pフラグを使って「useradd」を試しましたが、ログインしようとするとパスワードが間違っているというメッセージが表示されます。 「adduser」も試しましたが、まだ方法が見つかりませんでした。パスワードはユーザーが直接入力する必要があるようです。

私がしたいこと:1行のコマンドを使用してパスワードでユーザーアカウントを作成することをお勧めします。

これはパスワードなしでユーザーアカウントを作成する現在のPythonコードです。

#!/usr/bin/env python

import os
import openpyxl
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

excel_file = os.open("Names_mod.xlsx", os.O_RDONLY)
wb = openpyxl.load_workbook("Names_mod.xlsx")
sheet = wb.active
max_row = sheet.max_row

for i in range(1, max_row + 1):
    name = sheet.cell(row = i, column = 5)  
    password = sheet.cell(row = i, column = 6)
    addUser = "sudo useradd -m  " + name.value
    os.system(addUser)

ベストアンサー1

まだテストしていませんが、man useraddUbuntuですでに暗号化されたパスワードを渡す必要があるようです(これがおそらく以前は機能しなかった理由です)。

       -p, --password PASSWORD
           The encrypted password, as returned by crypt(3). The default is to disable the password.

           Note: This option is not recommended because the password (or encrypted password) will be visible by users listing the processes.

           You should make sure the password respects the system's password policy.

cryptモジュールはPython 2と3にあります。 Python 3では、crypt.crypt(password)を使用できます。

python3
Python 3.6.7 (default, Oct 22 2018, 11:32:17) 
[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import crypt
>>> crypt.crypt("hello")
'$6$AFKk6qImS5R6bf//$Voc7MRbOX5R2R8GvmmEHxVgx/wVorKO4y2Vuufgkph798mo/SJ6ON8vKJWj1JTsRdwNyb9oiTmHiNYGiOL4Q20'
>>> 

Python 2では、ソルトを2番目のパラメータとして渡す必要があります。ユーザーごとに異なる塩が選択されることに注意してください。

だからtl;dr python3でこれを試してみてください:

import crypt

...

for i in range(1, max_row + 1):
    name = sheet.cell(row = i, column = 5)  
    password = sheet.cell(row = i, column = 6)
    encrypted_password = crypt.crypt(password)
    addUser = "sudo useradd -m  " + name.value + " -p " + encrypted_password
    os.system(addUser)

編集:元のポスターによると、Python2では機能しないため、パスワードはまだ間違っています。 Python3でも実際のログインをテストしていません。 Python2の場合は動作しません。

for i in range(1, max_row + 1):
    name = sheet.cell(row = i, column = 5)  
    password = sheet.cell(row = i, column = 6)
    encrypted_password = crypt.crypt(password, name.value)
    # This doesnt work!
    addUser = "sudo useradd -m  " + name.value + " -p " + encrypted_password
    os.system(addUser)

おすすめ記事