Python的Pexpect的全输出不保存(如何对付“ - 更多 - ”提示?)

问题描述 投票:2回答:2

我使用Pexpect的在服务器上远程运行命令并保存在一个文件中的输出。然而,因为它是由于--More--截断它不保存整个输出。有没有办法避免--More--,使整个输出保存在输出文件?

我一直在使用child.setwinsize(1000,1000)尝试,但它并没有解决这个问题。

当前的代码:

import pexpect
import time

child = pexpect.spawn('ssh username@ip_address')
time.sleep(1)

child.sendline('password')
time.sleep(1)

child.logfile = open("output.txt", "w")
child.sendline('command')
child.expect(pexpect.EOF)

print child.before, child.after
child.close
python python-2.7 stdout pexpect
2个回答
1
投票

不知道是什么命令你正在运行,但通常当你看到--More--提示您可以按空格。例如:

import pexpect, sys

child = pexpect.spawn('more /etc/services')
child.logfile_read = sys.stdout

patterns = ['--More--', pexpect.EOF]
while True:
    ret = child.expect(patterns)
    if ret == 0:
        child.send(' ')
    elif ret == 1:
        break

1
投票

我发现多了一个答案 - 实际的命令之前,只需要执行下面的命令。

terminal length 0

之后,假设我进入像show ip interface一些命令。然后,这将显示整个输出。你并不需要按一次又一次的进入。如,

child.sendline('terminal length 0')   
child.expect('# ')    
child.sendline('show ip interface')   #write your command here
child.expect('# ') 
© www.soinside.com 2019 - 2024. All rights reserved.