在pexpect.before中执行了命令和意外数据

时间:2018-01-23 09:45:53

标签: python pexpect

我使用pexpect通过ssh连接到远程主机,并执行不同的命令来收集NetBackup(NBU)系统的统计数据。

import pexpect
import random
import string
import re

timeout = 600

spawn_kwargs = {'timeout': timeout, 'env': os.environ, 'ignore_sighup': False}
spawn = pexpect.spawn("ssh", **spawn_kwargs)

... # ssh authorization here

# prepare and send command
pattern = ''.join(random.sample(string.ascii_letters+string.digits, 20))
command = "'/usr/openv/volmgr/bin/vmquery' -h netbackup123 -a"
cmd = "%s %s echo %s" % (command, ";", pattern)
spawn.sendline(cmd.encode())

# expect response
patterns = [pexpectmod.EOF, pexpectmod.TIMEOUT, pattern.encode()]
expect_index = spawn.expect(patterns, timeout=timeout, searchwindowsize=1000)
if spawn.match == pexpect.TIMEOUT:
    logger.debug("got Timeout (set to %s). Got pexpect : %s", timeout, spawn.match)
    err = "Get response from session failed due timeout"
    logger.error(err)
    return -1

incoming = spawn.before.decode('utf-8', 'ignore')

# remove ANSI escape sequences
incoming = re.sub("\\x1b\[(\d+)m", "", incoming)
incoming = re.sub("\\x1b\[m", "", incoming)

print(incoming)
return 0

通常它运作良好,但有时我从pexpect得到了糟糕的输出。在pexpect的输出中有执行命令的全部或部分:

^[]0;root@netbackup123:~^G[root@netbackup123 ~]# '/usr/openv/volmgr/bin/vmquery' -h netbackup123 -a ; e ^Mcho TsiRdXP7NDMCqrwYFJ61
    ================================================================================
    media ID:              0001L1
    ...

有时候我还有其他意想不到的数据:

^[[A^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[K3
CLASS UNX_DSU1_MS_1streamFails71-1StreamSucceeds *NULL* 0 700000 190800 *NULL*
NAMES
...

我无法故意重现这一点。而这样的“随机”对我来说是个大问题:(

环境:

  • NBU主持人:CentOS 5.8
  • Pexpect主机:Red Hat Enterprise Linux Server 6.1版
  • Python:3.6.4
  • pexpect:3.2

有谁知道这种行为的原因? 谢谢!

1 个答案:

答案 0 :(得分:0)

这是一个功能,我已成功使用很长一段时间来删除ansi和不可怜的字符形成pexpect响应...看看它是否有助于你的情况。

public static void main(String[] args)