python - 如何通过Python脚本向Linux添加用户?

标签 python linux python-2.7 ubuntu

我一直在尝试通过 Python 脚本运行 Linux 终端命令,但到目前为止我似乎无法对我发现的内容执行任何操作。

这是我到目前为止所做的:

import os
import crypt

def addnewuser():

    uname=raw_input("Select Username")
    upass=raw_input("Select Password")

    #The encryption module seems to solve the obvious security leak,
    #but I still don't know whether even the exposed encrypted password is safe or not.
    ucrypt=crypt.crypt(upass,"123")
    os.system("useradd -m -p "+upass+" "+uname)

addnewuser()

This has been asked before ,但我似乎找不到解决方案,因为每当我运行脚本时,当我尝试在输入

时显示所有用户时,没有任何变化
compgen -u

在终端上。

更新 1:我想确保该过程的安全,并且我发现可以使用 stdout 文件来保护 sudo 密码不被记录在终端历史记录中。我如何用 python 编写来创建用户?

更新 2:我通过在代码中使用加密模块对用户密码进行加密,成功避免了一些安全漏洞。但如果入侵者有加密后的密码,那不是同样的事情吗?

<小时/>

这样做的主要目的是让我学习如何开发管理工具,最好是使用 Python。

<小时/>

我在 Ubuntu 16.04 上使用 Python 2.7 以及 PythonIDLE。

感谢您的帮助。

最佳答案

最肮脏的解决方案之一是运行

os.system("sudo useradd -m -p "+upass+" "+uname)

并添加到/etc/sudoers

user ALL=NOPASSWD: useradd

其中 user 是运行脚本的用户名。

同样非常不安全,强烈不推荐

关于python - 如何通过Python脚本向Linux添加用户?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42895671/

相关文章:

c++ - Linux C++编程:Why is the connection is . so,生成的可执行依赖库为.so.version

linux - 在 shell 脚本中配置 aws cli 的默认输出格式

django 模块导入错误 - python 2.7 与 python 3.4

python - 查询 Python 字典以从元组中获取值

linux - 使用 vim 设置 cscope

python - 根据日期范围合并数据框

python - 如何在 python 2.7 中使用 pyautogui 获取屏幕图像坐标

Python 获取 'permission denied' 到 Linux 中的文件

python - 如何将初始参数传递给 django 的 ModelForm 实例?

Python-从URL、里面的控制和特殊字符获取JSON