【问题标题】:Executed command and unexpected data in pexpect.beforepexpect.before 中执行的命令和意外数据
【发布时间】:2018-01-27 01:38:09
【问题描述】:

我使用 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
  • 预期:3.2

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

【问题讨论】:

标签: python pexpect


【解决方案1】:

这是我长期以来一直成功使用的一个函数,用于从 pexpect 响应中删除 ansi 和 non-pritable 字符...看看它是否对您的情况有帮助。

def rem_nonprintable_ctrl_chars(txt):
    """Remove non_printable ascii control characters """
    #Removes the ascii escape chars
    try:
        txt = re.sub(r'[^\x20-\x7E|\x09-\x0A]','', txt)
        # remove non-ascii characters
        txt = repr(txt).decode('unicode_escape').encode('ascii','ignore')[1:-1]
    except Exception as exception:
        print_exception(exception)
    return txt

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-11
    • 2013-04-16
    • 1970-01-01
    • 2015-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多