python - 在linux中使用Python创建SFTP用户

标签 python linux sftp

我创建了以下内容以在 Linux 服务器中创建 SFTP 用户。有没有更好的方法来实现这个?该脚本通过在检查用户是否已存在后生成用户名来工作。然后提示用户是要生成随 secret 码还是要创建自己的密码。之后,它获取用户名和密码并创建一个新用户,将它们添加到有权通过 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()

最佳答案

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

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

关于python - 在linux中使用Python创建SFTP用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26144613/

相关文章:

node.js - npm install 好像不对

linux - 在此处文档后使用 bash 语法

linux - 更改 Plesk 12 管理员电子邮件

ruby-on-rails - Rails Net::SFTP - 有没有办法使用 FTP 连接(而不是 sFTP)?

python - 打印未显示在 ipython 笔记本中

python - 地理 View ——墨卡托或 PlateCarree

python - 使用 Python 清理 HTML 内容

Linux:通过 ssh 连接自动传输 sftp 文件

ssh - 在 Google Compute Engine 上访问 FTP

Python sklearn 所有记录的余弦相似度循环