问题描述
我正在尝试自动设置 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
useraddcommand other than whether it failed or not, you might be better off usingsubprocess.check_callwhich will raise an exception if the command returns non-zero. - In the second case, you should check whether
process.returncodeis 0 after your call tocommunicate('test:password')
这篇关于如何通过 python 脚本在 linux 中设置用户密码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)