使用Python的pexpet与bash进行简单交互

本例子使用pexpet模块与bash进行简单交互,但要求输入密码时,输入设置好的密码。

import pexpect

PROMPT = "[$#]" # 正则匹配$或#

# get shell bash
def getBash():
    child = pexpect.spwn("/bin/bash")
    child.expect(PROMPT) # 等待用户输入
    return child

child = getBash()
# set log file.
log = file('./demo.log', 'w')
child.logfile = log

child.sendline("su") # 获取管理员权限
# when bash need password
child.expect("password") # 拦截到需要输入密码
# enter you password
child.sendline('yourPassword')

child.expect(PROMPT) # 等待用户输入
child.send("your command") # 输入你的命令
......

output = child.read() # 读取bash中的输出
print(output)
child.close() # 关闭
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容