如何从python脚本在linux中设置用户密码? [英] How can I set a users password in linux from a python script?

查看:90
本文介绍了如何从python脚本在linux中设置用户密码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我可以像这样创建用户:

<预><代码>>>>导入子流程>>>process = subprocess.Popen(['sudo', 'useradd', 'test'], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)>>>process.communicate()('', '')

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

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

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

最好的方法是什么?

我在 Ubuntu lucid 上运行 python 2.6.

解决方案

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

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

我很欣赏这只是骨架代码,但这里还有一些其他的小注释,以防万一:

  • 如果您对 useradd 命令的输出除了它是否失败之外不感兴趣,您最好使用 subprocess.check_call 这会引发如果命令返回非零则异常.
  • 在第二种情况下,您应该在调用 communicate('test:password')
  • 后检查 process.returncode 是否为 0

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

I can create a user like so:

>>> 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')

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

What's the best way to do this?

I'm running python 2.6 on Ubuntu lucid.

解决方案

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:

  • 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中设置用户密码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆