【发布时间】: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
有人知道这种行为的原因吗? 谢谢!
【问题讨论】:
-
这些看起来也像ANSI escape sequences。