【问题标题】:How can I automate the user creation in Linux servers using Python如何使用 Python 在 Linux 服务器中自动创建用户
【发布时间】:2019-07-19 17:43:26
【问题描述】:

我正在尝试创建一个脚本来自动在 Linux 服务器中创建用户,因此我在每个服务器中生成了 ssh 密钥并编写了如下代码:

user = teste
p = 'senha123' 
os.system("ssh myuser@lab sudo useradd -p " + p + " -d "+ "/home/" + user+ " -m "+ " -c \""+ name+"\" " + user)`

但是,我得到了错误:

Usage: useradd [options] LOGIN useradd -D useradd -D [options]

Options: -b, --base-dir BASE_DIR base directory for the home directory of the new account -c, --comment COMMENT GECOS field of the new account -d, --home-dir HOME_DIR home directory of the new account -D, --defaults print or change default useradd configuration -e, --expiredate EXPIRE_DATE expiration date of the new account -f, --inactive INACTIVE password inactivity period of the new account -g, --gid GROUP name or ID of the primary group of the new account -G, --groups GROUPS list of supplementary groups of the new account -h, --help display this help message and exit -k, --skel SKEL_DIR use this alternative skeleton directory -K, --key KEY=VALUE override /etc/login.defs defaults -l, --no-log-init do not add the user to the lastlog and faillog databases -m, --create-home create the user's home directory -M, --no-create-home do not create the user's home directory -N, --no-user-group do not create a group with the same name as the user -o, --non-unique allow to create users with duplicate (non-unique) UID -p, --password PASSWORD encrypted password of the new account -r, --system create a system account -R, --root CHROOT_DIR directory to chroot into -s, --shell SHELL login shell of the new account -u, --uid UID user ID of the new account -U, --user-group create a group with the same name as the user -Z, --selinux-user SEUSER use a specific SEUSER for the SELinux user ma pping

512

当我删除 ssh myuser@lab 部分时,脚本在 localhost 中运行。

有人可以帮我解决这个问题吗?

【问题讨论】:

标签: python linux shell devops


【解决方案1】:

您将 ssh 视为使用 execve(2) 语义,将命令和参数作为单独的参数传递(sudo、xargs 和 find -exec 的工作方式)。

ssh 改为使用 system(3) 语义,因此它需要单个文字 shell 命令(如 su、eval、bash -c 和 Python 的 os.system)。

对任意命令执行此操作的一种通用方法是首先将要运行的 shell 命令分配给另一个字符串:

remote_command="sudo useradd -p " + p + " -d "+ "/home/" + user+ " -m "+ " -c \""+ name+"\" " + user

然后使用shlex.quote 将其转义为ssh:

import shlex
os.system("ssh myuser@lab " + shlex.quote(remote_command))

或者,跳过system() 以避免添加另一层转义:

import subprocess
subprocess.run(["ssh", "myuser@lab", remote_command], shell=False)

【讨论】:

  • 感谢您的详细解答。它工作并帮助我更好地理解 pyhton 和 shell 行为。
【解决方案2】:

我不太确定它是否会起作用,但你可以尝试一次吗:

os.system("ssh myuser@lab \'sudo useradd -p " + p + " -d "+ "/home/" + user+ " -m "+ " -c \""+ name+"\" " + user+"\'")

【讨论】:

  • 感谢您的回答,但是os模块在传递许多参数时会感到困惑,然后它就不起作用了。
猜你喜欢
  • 2011-03-12
  • 2021-05-17
  • 2015-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多