Python – Script7: Configure Network Device via SSH (Paramiko)

Step1: Install python on Windows/Linux or run ‘Network Automation Appliance’ on GNS3 which has pre-installed python & Paramiko

Step2: Install Paramiko
Install Paramiko
apt-get update
apt-get install python -y
apt-get install build-essential libssl-dev libffi-dev -y
apt-get install python-pip –y
apt-get installpython-dev # You may need to install this as well
 
pip install cryptography
pip install paramiko

Step3: To verify is Paramiko is installed or not:
	>>> import paramiko
>>> print paramiko.__version__

Step4: Configure router for SSH
	Hostname SW1
	Int gi0/0
		ip add 192.168.10.21 255.255.255.0
 		No sh
	ip domain-name s4u.in
	crypto key generate rsa		1024 bits
	enable password cisco
	username rachit password cisco
	line vty 0 4
		login local
		transport input all

Step5: Make sure you are able to ping Network Automation device.

Step6: Below Python script to run on GNS3 Appliance – Network Automation. Script will make SSH connection to device and configure loopbacks, OSPF protocols with Vlans
import paramiko
import time
 
ip_address = “192.168.10.21”
username = “rachit”
password = “cisco”
 
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(hostname=ip_address,username=username,password=password)
 
print “Successful connection”, ip_address
 
remote_connection = ssh_client.invoke_shell()
 
remote_connection.send(“enable\n”)
remote_connection.send(“cisco\n”)
remote_connection.send(“configure terminal\n”)
remote_connection.send(“int loop 0\n”)
remote_connection.send(“ip address 1.1.1.1 255.255.255.255\n”)
remote_connection.send(“exit\n”)
remote_connection.send(“int loop 1\n”)
remote_connection.send(“ip address 2.2.2.2 255.255.255.255\n”)
remote_connection.send(“exit\n”)
remote_connection.send(“router ospf 1\n”)
remote_connection.send(“network 0.0.0.0 255.255.255.255 area 0\n”)
remote_connection.send(“exit\n”)
 
for n in range (2,20):
    print “Creating VLAN ” + str(n)
    remote_connection.send(“vlan ” + str(n) +  “\n”)
    remote_connection.send(“name Python_VLAN ” + str(n) +  “\n”)
    time.sleep(0.5)
 
remote_connection.send(“end\n”)
 
time.sleep(20)
output = remote_connection.recv(65535)
print output
 
ssh_client.close

Network Architect | CCIEx3 #29824 JNCIE #2197 VCIX-NV

Leave a Comment