如何通过 python 脚本在 Linux 中设置用户密码?
我正在尝试自动设置 SFTP 访问。该脚本以具有 sudo 权限但没有密码的用户身份运行。
我可以像这样创建一个用户:
>>> import subprocess
>>> 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。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
尝试下面的代码,它将按照您的要求执行自动化
print
语句是可选的。Try below code which will do as you required automation
print
statements are optional.communicate
的文档指出,如果您通过communicate
参数将数据发送到标准输入,则需要添加stdin=PIPE
:http://docs.python.org/release/2.6 /library/subprocess.html#subprocess.Popen.communicate
我很欣赏这只是骨架代码,但这里还有另外几个其他小注释,以防它们有用:
useradd
命令是否失败之外,您可能最好使用subprocess.check_call
,如果命令返回非零,它会引发异常。communicate('test:password')
后检查process.returncode
是否为 0The documentation for
communicate
says that you'll need to addstdin=PIPE
if you're sending data to standard input via thecommunicate
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
command other than whether it failed or not, you might be better off usingsubprocess.check_call
which will raise an exception if the command returns non-zero.process.returncode
is 0 after your call tocommunicate('test:password')
在 Ubuntu 上,使用 usermod
On Ubuntu, use usermod
您忘记了这一点:
要将数据发送到进程,您需要一个
stdin
。所以完整的语句是:
然后调用
communicate('password')
。You forgot this:
To send data to the process, you need a
stdin
.So the full statement is:
and then call
communicate('password')
.我猜问题是你忘记了 sudo 的 -S 选项。
I guess the issue is that you forgot the -S option for sudo.