gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 01:16:39 29 4
gpt4 key购买 nike

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

关于python - 如何以 sudo 用户身份执行 pexpect spawn 命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54285397/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com