我正在尝试自动设置 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
是否为 0useradd
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.process.returncode
is 0 after your call to communicate('test:password')
这篇关于如何通过 python 脚本在 linux 中设置用户密码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!