python - 如何使用 python 脚本将参数传递给 linux 命令提示符

标签 python linux shell devops system-administration

演示.py

import os
f = os.popen('passwd')

输出:

Enter Existing Password: (This one I want program enter)

我正在运行这个提示我输入现有密码的 python 程序。但我想通过程序发送现有密码。

有什么方法可以通过程序将该值传递给命令提示符。

最佳答案

我们可以通过使用 python 的 expect 模块来实现这一点。我写了示例代码:

#!/usr/bin/python
import pexpect
import sys
child = pexpect.spawn('passwd')
child.logfile=sys.stdout
child.expect("UNIX password:")
child.sendline('guest')
child.expect('Enter new UNIX password:')
child.sendline('guest')
child.expect('Retype new UNIX password:')
child.sendline('guest')

您还可以在 http://www.pythonforbeginners.com/systems-programming/how-to-use-the-pexpect-module-in-python 查看 expect 模块的更多详细信息

关于python - 如何使用 python 脚本将参数传递给 linux 命令提示符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37034585/

相关文章:

linux - 比较 2 个文件中的两列并使用 awk 替换另一列

bash - 如何处理 bash 安装脚本中的相对路径?

linux - Xmonad,如何绑定(bind)一个键来运行一个shell脚本?

python - Flask-MySQL 如何使用参数化查询有效 INSERT INTO 表

python - 精度比 gridsearchCV 低

linux - 用于计算应用程序内存的 Bash 脚本

C++ - Linux 上的光标移动

linux - 命令行打开一个窗口

python - Django FilterSet AND(?)条件

python - 尝试在每个数据帧列条目中搜索与 'Id' 对应的值时出现内存错误