На основе предыдущего скрипта сделал сбор информации и подсчет подходящих под условие
отличие здесь довольно простое
из функции есть возрат значения, а уже значение (по сути ответ устройства) анализируется на наличие строк.
поиск строки сделан очень просто просто проверяется строка целиком с помощью in.
#!/usr/bin/python
#for work with SSH we need paramiko pip install paramiko
import paramiko
#hide password input
import getpass
#build in library socket for with exception
import socket
list_bad_ip=[]
receive_buffer=""
client = paramiko.SSHClient()
#for connection via ssh you need to accept SSH keys
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
#create function for send command and check answer
def send_string_and_wait_for_string(command, wait_string):
#send command
shell.send(command)
#clear buffer
receive_buffer = ""
#until receive WAIT_STRING - remote device ready
while not wait_string in receive_buffer:
receive_buffer += shell.recv(1024)
#return buffer with output of command
return receive_buffer
#read list of IPs from text file one by line
ips = [i.strip() for i in open("./1")]
username1 = raw_input("enter login :")
#hide password input
password1 = getpass.getpass("enter password :")
#create loop for each IPs
for ip in ips:
#if we use try easy to work with expection
try:
#connect to device
client.connect(ip,port=22,username=username1,password=password1)
#check state
# print "connect to ",ip
shell = client.invoke_shell()
#wait for enable
send_string_and_wait_for_string("", "#")
#enter command and wait for return to #
receive_buffer = send_string_and_wait_for_string("sh int Vlan12 | i line protocol\n","#")
#first option not interesting
if "line protocol is up" in receive_buffer:
print ip+" protocol is up"
#second possible answer interesting save in separate list
else:
print ip+" line protocol is down"
list_bad_ip.append(ip)
#close with this device
shell.close()
client.close()
#work with timeout error
except socket.error:
print ip + '=== Device unreachable'
#add ip with errors to list
list_bad_ip.append(ip)
#save this list to file
with open('bad_ip', 'w') as f:
for s in list_bad_ip:
f.write(s + '\n')
#show list at the screen for lazy admin
print list_bad_ip
(END)