Why do I get "OSError: [Errno 2] No such file or directory" when running this script?

StackOverflow https://stackoverflow.com/questions/19628028

  •  01-07-2022
  •  | 
  •  

Question

First of all, here is my code:

#!/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])

When I run this script I get this error code:

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

I am trying to add users with passwords and comments from an excel file. I don't get what I'm doing wrong. Can someone please explain this for me?

Thanks!

Was it helpful?

Solution

You should pass all args to subprocess.call in separate elements of a list, try

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

I replaced your password username to 'password' since '-p' argument to useradd must be encripted with crypt. Following snippet will help you with this:

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())

If you want password to equal username, use

subprocess.call(['useradd', '-c', comment, 'username', '-p', 
    encript_pwd(username)])
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top