2016-03-21 111 views
-1

我試圖從顯示庫存中獲取開關的模型no,然後將整數設置爲交換機所具有的端口數量。 ive試圖讓結果進入一行,然後用正則表達式搜索(正則表達式的作品,我測試它在http://regexr.com/python - 函數不返回完整輸出

它看起來不像我的函數正在返回完整的庫存,它被截斷。它應該返回下面的

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() 
+1

寫'不是在b'中是不好的形式。相反,你應該使用'a not in b'。 –

+0

,似乎已經修復了輸出,objInv字符串現在已填充,但strInv是關於此的任何想法 – AlexW

+0

?掙扎很多... – AlexW

回答

0

更換新線路和休息,並用找到的,而不是正則表達式和其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