如何通过 python 脚本在 linux 中设置用户密码?

How can I set a users password in linux from a python script?(如何通过 python 脚本在 linux 中设置用户密码?)
本文介绍了如何通过 python 脚本在 linux 中设置用户密码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试自动设置 SFTP 访问.此脚本以具有 sudo 权限且没有密码的用户身份运行.

I'm trying to automate the setup of SFTP access. This script is running as a user with sudo permissions and no password.

我可以这样创建用户:

>>> import subprocess
>>> process = subprocess.Popen(['sudo', 'useradd', 'test'], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
>>> process.communicate()
('', '')

接下来我需要设置用户的密码,但我不知道如何设置.这是我尝试过的.

Next I need to set the user's password, but I can't figure out how. Here's what I've tried.

>>> process = subprocess.Popen(['sudo', 'chpasswd'], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
>>> process.communicate('test:password')

在我的 python 程序中它没有效果,在交互式解释器中它在第一行之后锁定.

In my python program it has no effect, in the interactive interpreter it locks up after the first line.

最好的方法是什么?

我在 Ubuntu lucid 上运行 python 2.6.

I'm running python 2.6 on Ubuntu lucid.

推荐答案

communicate 的文档说你需要添加 stdin=PIPE 如果你是通过 communicate 参数将数据发送到标准输入:

The documentation for communicate says that you'll need to add stdin=PIPE if you're sending data to standard input via the communicate parameter:

http://docs.python.org/release/2.6/library/subprocess.html#subprocess.Popen.communicate

我很欣赏这只是框架代码,但这里还有另外几个小注释,以防它们有用:

I appreciate this is just skeleton code, but here are another couple of other small comments, in case they are of use:

  • 如果您对 useradd 命令的输出不感兴趣,而不是它是否失败,您最好使用 subprocess.check_call 会引发如果命令返回非零,则异常.
  • 在第二种情况下,您应该在调用 communicate('test:password')
  • 后检查 process.returncode 是否为 0
  • If you're not interested in the output of the useradd command other than whether it failed or not, you might be better off using subprocess.check_call which will raise an exception if the command returns non-zero.
  • In the second case, you should check whether process.returncode is 0 after your call to communicate('test:password')

这篇关于如何通过 python 脚本在 linux 中设置用户密码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)