1

首先,这是我的代码:

#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
from xlrd import open_workbook
import subprocess
import sys

START_ROW = 0
col_name = 0
col_room = 2
col_phone = 3
col_usr_name = 4
col_password = 5

book = open_workbook('Names_mod.xls',formatting_info=True)
sheet = book.sheet_by_index(0)

for row_index in range(START_ROW, sheet.nrows): 
    username = sheet.cell(row_index, col_usr_name).value
    pwrd = sheet.cell(row_index, col_password).value
    name = sheet.cell(row_index, col_name).value
    room = sheet.cell(row_index, col_room).value
    room = ''.join(i for i in pwrd if i.isdigit())
    phone = sheet.cell(row_index, col_phone).value
    phone = ''.join(i for i in pwrd if i.isdigit())
    comment = name".", room".", phone"."
    if col_name != "":
        subprocess.call(['useradd -c', comment, username])
        subprocess.call(['passwd', username])

当我运行这个脚本时,我得到这个错误代码:

Traceback (most recent call last):
File "./lab5uppgift2.py", line 30, in <module>
    subprocess.call(['useradd -c', comment, username])
File "/usr/local/lib/python2.7/subprocess.py", line 524, in call
    return Popen(*popenargs, **kwargs).wait()
File "/usr/local/lib/python2.7/subprocess.py", line 711, in __init__
    errread, errwrite)
File "/usr/local/lib/python2.7/subprocess.py", line 1308, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory

我正在尝试使用 Excel 文件中的密码和注释添加用户。我不明白我做错了什么。有人可以为我解释一下吗?

谢谢!

4

1 回答 1

2

您应该将所有参数传递subprocess.call给列表的单独元素,尝试

subprocess.call(['useradd', '-c', comment, 'username', '-p', 'password'])

我将您的密码替换username'password''-p' 参数useradd必须用crypt. 以下代码段将帮助您解决此问题:

import os
import crypt
import random

saltchars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"

def salt():
    return random.choice(saltchars) + random.choice(saltchars)

def encript_pwd(password):
    return crypt.crypt(password,salt())

如果您希望密码等于用户名,请使用

subprocess.call(['useradd', '-c', comment, 'username', '-p', 
    encript_pwd(username)])
于 2013-10-28T06:02:30.673 回答