【问题标题】:python - function not returning full outputpython - 函数未返回完整输出
【发布时间】:2016-03-21 21:30:05
【问题描述】:

我试图从显示清单中获取交换机的型号,然后将整数设置为交换机拥有的端口数。我试图让结果进入一行,然后用正则表达式搜索(我在http://regexr.com/上测试了正则表达式)

看起来我的函数没有返回完整的库存,它被切断了。它应该返回以下内容

Switch#sh inventory
NAME: "1", DESCR: "WS-C2960X-24PS-L"
PID: WS-C2960X-24PS-L  , VID: V01  , SN: XXXXX

这是我得到的输出

Switch#
Switc
Object is: terminal length 0
Switch#sh inventory
NAME:
Inventory is:
Port Count is: 0

这是脚本

#!/usr/bin/env python

import paramiko
import time
import sys
import re

# For debugging only
#paramiko.common.logging.basicConfig(level=paramiko.common.DEBUG)

#
interface_regex = "interface GigabitEthernet[1-5]\/0\/"

def Send_Command_and_Get_Response(command, reponse, result):
    # Send the su command
    shell.send(command)

    # Create a new receive buffer
    receive_buffer = ""

    while not reponse in receive_buffer:
        # Flush the receive buffer
        receive_buffer += shell.recv(1024)

    # Print the receive buffer, if necessary
    if result:
        print receive_buffer

    return receive_buffer   

# VARIABLES THAT NEED CHANGED
ip = '10.X.X.X'
username = 'root'
password = 'XXXX'
port = 3010

# Create instance of SSHClient object
client = paramiko.SSHClient()

# Make sure that we add the remote server's SSH key automatically
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())


# initiate SSH connection
client.connect(ip, username=username, password=password,port=port, look_for_keys=False, allow_agent=False)
print "SSH connection established to %s" % ip

# Use invoke_shell to establish an 'interactive session'
shell = client.invoke_shell()


print "Interactive SSH session established"
time.sleep(1)
shell.send("\r\n")
output = shell.recv(1000)
print output


# Disable more
Send_Command_and_Get_Response("terminal length 0\n", "#", False)

objInv = Send_Command_and_Get_Response("sh inventory\n", "#", False)
strInv =""
strInv.join(objInv.splitlines())

intPort = 0
if (re.match("WS-C.*24", strInv)):
    intPort = 24
elif (re.match("WS-C.*48", strInv)):
    intPort = 48

print "Object is: " + objInv
print "Inventory is: " + strInv
print "Port Count is: " + str(intPort)


# Close the SSH connection
client.close()

【问题讨论】:

  • not a in b 是不好的形式。相反,您应该使用a not in b
  • 这似乎已经修复了输出,现在填充了 objInv 字符串但 strInv 是 emtpy
  • 对此有什么想法吗?苦苦挣扎……

标签: python ssh paramiko


【解决方案1】:

替换新行和换行符并使用 find 代替 regex 及其 fixex!

objInv = Send_Command_and_Get_Response("sh inventory\n", "#", False)
print "Object is: " + objInv

strInv = str(objInv)
strInv = strInv.replace('\n','').replace('\r','')

intPort = 0
if (strInv.find('WS-C') >-1 and strInv.find('-24') >-1):
    intPort = 24
if (strInv.find('WS-C') >-1 and strInv.find('-48') >-1):
    intPort = 48

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-04
    • 2011-11-25
    • 1970-01-01
    • 2014-11-10
    相关资源
    最近更新 更多