如何使用Pexpect执行root命令? [英] How to perform a root command with Pexpect?

查看:56
本文介绍了如何使用Pexpect执行root命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个python程序来协助apt-get工具.我想使用pexpect下载所选的软件包.我相信我会卡在child.expect行上.该行似乎超时.

I'm working on a python program to assist with the apt-get tool. I want to use pexpect to download the chosen package. I believe I'm getting stuck at the child.expect line. It seems to timeout when it comes to that line.

butt = "vlc"
child = pexpect.spawn('sudo apt-get install ' + butt)
child.logfile = sys.stdout
child.expect('[sudo] password for user1: ')
child.sendline('mypassword')

这是日志文件.

TIMEOUT: Timeout exceeded.
<pexpect.spawn object at 0xb5ec558c>
version: 3.2
command: /usr/bin/sudo
args: ['/usr/bin/sudo', 'apt-get', 'install', 'vlc']
searcher: <pexpect.searcher_re object at 0xb565710c>
buffer (last 100 chars): '[sudo] password for user1: '
before (last 100 chars): '[sudo] password for user1: '
after: <class 'pexpect.TIMEOUT'>
match: None
match_index: None
exitstatus: None
flag_eof: False
pid: 27641
child_fd: 4
closed: False
timeout: 30
delimiter: <class 'pexpect.EOF'>
logfile: <open file '<stdout>', mode 'w' at 0xb74d8078>
logfile_read: None
logfile_send: None
maxread: 2000
ignorecase: False
searchwindowsize: None
delaybeforesend: 0.05
delayafterclose: 0.1
delayafterterminate: 0.1

更新:

密码发送就很好了.它还期望下一行,但随后输入"Y"却什么也不做.

The password gets sent just fine. It also expects the next line as well, but then enters "Y" and does nothing.

child = pexpect.spawn('sudo apt-get install ' + butt)
child.logfile = sys.stdout
child.expect_exact('[sudo] password for user1: ')
child.sendline('mypass')
child.expect_exact('Do you want to continue? [Y/n] ')
child.sendline('Y')

已解决:

我需要在最后添加这一行.

I needed to add this line at the end.

child.expect(pexpect.EOF, timeout=None)

推荐答案

尝试 child.expect_exact().

从文档中

Expect()方法等待子应用程序返回给定的字符串.您指定的字符串是一个正则表达式,因此您可以匹配复杂的模式.

The expect() method waits for the child application to return a given string. The string you specify is a regular expression, so you can match complicated patterns.

最好仅在意图匹配正则表达式时使用 expect().

It is good practice to use expect() only when the intent is to match a regular expression.

这篇关于如何使用Pexpect执行root命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆