rbart65 rbart65 - 1 year ago 90
Linux Question

Using Python to create SFTP users in linux

I created the following to create SFTP users in a linux server. Is there a better way to implement this? The script works by generating a username after checking if the user already exists. Then prompts the user if they want to generate a random password or if they want to create their own. Afterwords, it takes the username and password and creates a new user adding them to a group that has permissions to upload via sftp. I'm mostly concerned with using os.system a lot.

#!/usr/bin/env python

import pwd
import string
import random
import os
from getpass import getpass

def generate():
global username
username = raw_input("Enter username: ")
print "Username already exists."
return username

def pass_generator():
global password
confirm = raw_input("Randomly generate password? (y/n): ")
if confirm == "y":
password = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for _ in range(6))
elif confirm == "n":
p1 = getpass("Enter password: ")
p2 = getpass("Confirm password: ")
if p1 == p2:
password = p1
print "Passwords do not match. Try again."
print "Type y for yes, n for no."

def create_account(Username, Password):
os.system('sudo useradd -d /home/clients/%s -s /usr/libexec/openssh/sftp-server -g sftp-only %s' % (Username, Username))
os.system('sudo chown root:integration /home/clients/%s' % (Username))
os.system('sudo chmod 777 /home/clients/%s' % (Username))
os.system('echo %s:%s | sudo chpasswd' % (Username, Password))

def main():
create_account(username, password)
print "User %s has been successfully created with password %s" % (username, password)

if __name__ =='__main__':main()

Answer Source

you could use subprocess.popen(). It's safer than os.system, and gives you access to the standard buffers as well.