首页 > 解决方案 > 如何以 sudo 用户身份执行 pexpect spawn 命令?

问题描述

我正在尝试以 sudo 执行 pexpect spawn 命令并出现超时错误

import pexpect,os,commands,getpass
child = pexpect.spawn ('su - oracle -c "/home/Middleware/bin/emctl  status oms -details"')
child.expect("Enter Enterprise Manager Root (SYSMAN) Password :")
child.sendline("welcome1")
child.expect(pexpect.EOF, timeout=None)
cmd_show_data = child.before
cmd_output = cmd_show_data.split('\r\n')
for data in cmd_output:
    print data

下面是执行输出:

pexpect.TIMEOUT: Timeout exceeded in read_nonblocking().
<pexpect.spawn object at 0x9ae510>
version: 2.3 ($Revision: 399 $)
command: /bin/su
args: ['/bin/su', '-', 'oracle', '-c', '/home/Middleware/bin/emctl status oms -details']
searcher: searcher_re:
    0: re.compile("Enter Enterprise Manager Root (SYSMAN) Password :")
buffer (last 100 chars): , 2016 Oracle Corporation.  All rights reserved.
Enter Enterprise Manager Root (SYSMAN) Password :
before (last 100 chars): , 2016 Oracle Corporation.  All rights reserved.
Enter Enterprise Manager Root (SYSMAN) Password :
after: <class 'pexpect.TIMEOUT'>

标签: pythonpexpect

解决方案


这是因为您的搜索字符串在编译为正则表达式时与输出不匹配。

根据spawn.expect文档:

该模式可以是 StringType、EOF、已编译的 re 或任何这些类型的列表。字符串将被编译为重新类型

问题是括号,它们是正则表达式中的特殊字符,当打算被视为文字时必须用反斜杠转义。

print(re.match("Enter Enterprise Manager Root (SYSMAN) Password :",
               "Enter Enterprise Manager Root (SYSMAN) Password :"))

# Prints: None

print(re.match("Enter Enterprise Manager Root \(SYSMAN\) Password :",
               "Enter Enterprise Manager Root (SYSMAN) Password :"))

# Prints: <_sre.SRE_Match object; span=(0, 49), match='Enter Enterprise Manager Root (SYSMAN) Password :>

推荐阅读