Python

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 4

Python, Paramiko SSH, and Network Devices

>>> import paramiko


>>> ip = '1.1.1.16'
>>> username = 'testuser'
>>> password = 'password'
>>> remote_conn_pre=paramiko.SSHClient()
>>> remote_conn_pre
>>> remote_conn_pre.set_missing_host_key_policy (paramiko.AutoAddPolicy())
>>> remote_conn_pre.connect(ip, username=username, password=password,
look_for_keys=False, allow_agent=False)

SSH into Cisco device and run show commands


from Exscript.util.interact import read_login
from Exscript.protocols import SSH2

account = read_login()
conn = SSH2()
conn.connect('192.168.1.11')
conn.login(account)
conn.execute('terminal length 0')
conn.execute('show version')
print conn.response
conn.send('exit\r')
conn.close()

Check whether a network interface is up


import sys,pexpect,getpass,time

username = raw_input("Username: ")


password = getpass.getpass()

routerFile = open('devicelist', 'r')


routers = [i for i in routerFile]
for router in routers:
try:
child = pexpect.spawn ('telnet', [router.strip()])
child.expect(['[uU]sername:', '[lL]ogin:'], timeout=3)
child.sendline(username)
child.expect('[pP]assword:')
child.sendline(password)
software = child.expect([ '#'], 6)
print ("Logging into " + router.strip())
except:
print "\nCould not log in to " + router.strip()
pass
commandlist = 'junos'
commands = open(commandlist, 'r')
for command in commands:
command.strip()
child.sendline(command.strip())
child.expect(['>'],20)
print child.before
These are the commands I'm trying to send:

show interface terse | no-more | match lo


show interfaces descriptions

from pyroute2 import IPRoute


ip = IPRoute()
state = ip.get_links(ip.link_lookup(ifname='em1'))[0].get_attr('IFLA_OPERSTATE')
ip.close()

ping process
import subprocess
import os
with open(os.devnull, "wb") as limbo:
for n in xrange(1, 10):
ip="192.168.0.{0}".format(n)
result=subprocess.Popen(["ping", "-c", "1", "-n", "-W", "2", ip],
stdout=limbo, stderr=limbo).wait()
if result:
print ip, "inactive"
else:
print ip, "active"

import shlex
import subprocess

# Tokenize the shell command


# cmd will contain ["ping","-c1","google.com"]
cmd=shlex.split("ping -c1 google.com")
try:
output = subprocess.check_output(cmd)
except subprocess.CalledProcessError,e:
#Will print the command failed with its exit status
print "The IP {0} is NotReacahble".format(cmd[-1])
else:
print "The IP {0} is Reachable".format(cmd[-1])

Traceroute
traceroute = subprocess.Popen(["traceroute", '-w',
'100',hostname],stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in iter(traceroute.stdout.readline,""):
print(line)

import socket
socket.gethostbyname(socket.gethostname())

Valid IP:
def is_valid_ip(ip):
m = re.match(r"^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$", ip)
return bool(m) and all(map(lambda n: 0 <= int(n) <= 255, m.groups()))

def validIP(address):
parts = address.split(".")
if len(parts) != 4:
return False
for item in parts:
if not 0 <= int(item) <= 255:
return False
return True

MAC:
if re.match("[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$", x.lower()):

Reading and Writing Files in Python


Open()

file_object = open(filename, mode) where file_object is the variable to put the


file object.

'r' when the file will only be read


'w' for only writing (an existing file with the same name will be erased)
'a' opens the file for appending; any data written to the file is automatically
added to the end.
'r+' opens the file for both reading and writing.
Create a text file
file = open("newfile.txt", "w")
file.write("hello world in the new file\n")
file.write("and another line\n")
file.close()

read
file = open('newfile.txt', 'r')
print file.read()
looping
file = open('newfile.txt', 'r')
for line in file:
print line

You might also like