Wednesday, 27 September 2017

Python for network engineer:- Configure multiple router using SSH :- Python2.7

import paramiko
import time
import sys
import logging
import socket

remote_conn_pre = paramiko.SSHClient()
remote_conn_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy())

# store router ip in ip.txt file in same folder where script is.
ips = [i.strip() for i in open("ip.txt")]

g = open('config.txt', 'r+')# store configuration in config.txt file in same folder where script is.
str = g.read()
g.close

for ip in ips:
    try:
        remote_conn_pre.connect(ip, username='test', password='test', timeout=4, look_for_keys=False, allow_agent=False)

        remote_conn = remote_conn_pre.invoke_shell()
        print (ip + ' === Device Reachable')
        remote_conn.send("\n")
        remote_conn.send((str))
        time.sleep(2)
        #output = remote_conn.recv(5000)
        #print (output)
    except paramiko.AuthenticationException:
        print ip + ' === Bad credentials'
    except paramiko.SSHException:
        print ip + ' === Issues with ssh service'
    except socket.error:
        print ip + ' === Device unreachable'

No comments:

Post a Comment