使用Python在linux中创建SFTP用户

时间:2014-10-01 15:12:37

标签: python linux sftp

我创建了以下内容以在Linux服务器中创建SFTP用户。有没有更好的方法来实现这个?该脚本通过在检查用户是否已存在之后生成用户名来工作。然后提示用户是否要生成随机密码,或者是否要创建自己的密码。之后,它会获取用户名和密码,并创建一个新用户,将其添加到有权通过sftp上传的组中。我最关心的是使用os.system。

#!/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: ")
        try:
                pwd.getpwnam(username)
                print "Username already exists."
                generate()
        except:
                pass_generator()
                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
                else:
                        print "Passwords do not match. Try again."
                        pass_generator()
        else:
                print "Type y for yes, n for no."
                pass_generator()

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():
    generate()
    create_account(username, password)
    print "User %s has been successfully created with password %s" % (username, password)

if __name__ =='__main__':main()

1 个答案:

答案 0 :(得分:1)

您可以使用subprocess.popen()。它比os.system更安全,并且您还可以访问标准缓冲区。

https://docs.python.org/2/library/subprocess.html