我试图从显示库存中获取模型no切换然后将整数设置为交换机具有的端口号。香港专业教育学院试图让结果进入一行然后用正则表达式搜索(正则表达式工作我在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()
答案 0 :(得分:0)
替换了新行和符号并使用了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