如何以 sudo 用户身份执行 pexpect spawn 命令?

How to execute pexpect spawn comand as sudo user?

我正在尝试以 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'>

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

根据 spawn.expect 文档:

The pattern can be a StringType, EOF, a compiled re, or a list of any of those types. Strings will be compiled to re types.

问题出在圆括号上,它们是正则表达式中的特殊字符,在被视为文字时必须使用反斜杠进行转义。

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 :>