Im trying to get the model no of a switch from show inventory then set a integer to the no of ports the switch has. ive tried to make the result go onto one line and then search that with regex (the regex works i tested it on http://regexr.com/)
It doesn't look like my function is returning the full inventory, its getting cut off. it should return the below
Switch#sh inventory
NAME: "1", DESCR: "WS-C2960X-24PS-L"
PID: WS-C2960X-24PS-L , VID: V01 , SN: XXXXX
This is the output im getting
Switch#
Switc
Object is: terminal length 0
Switch#sh inventory
NAME:
Inventory is:
Port Count is: 0
and this is the script
#!/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()
replaced new lines and breaks and used find instead of regex and its 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
Related
So this script is meant to telnet into a router and change the IP address on the given interface. However, my script runs into errors and I'm not sure why. The line that errors out is line 44.
This is my python script:
import os
import sys
import telnetlib
if (len(sys.argv) != 3):
print "syntax: python hw06.py <device> <newip>"
sys.exit()
router = sys.argv[1]
newip = sys.argv[2]
interface = "Serial0/0" # must hard code the interface to avoid disaster
TIMEOUT = 3
password1 = "user"
password2 = "cisco"
cmd = "ip address 111.11.111.11 255.255.255.0"
# 1. create a telnet object
tn = telnetlib.Telnet(router, timeout=TIMEOUT)
# 2. login/telnet to the router
tn.read_until("Password: ", TIMEOUT)
tn.write(password1 + "\n")
# 3. enter into the privilege mode
tn.write("enable\n")
tn.read_until("Password:")
tn.write(password2 + "\n")
# 4. enter into the configuration mode
tn.write("configure terminal\n")
tn.read_until("(config)#", TIMEOUT)
# 5. enter into the interface configuration mode
tn.write("int" + interface + "\n")
tn.read_until("(config-if)#", TIMEOUT)
# 6. set the new IP address
tn.write(cmd + "\r\n")
# 7. exit
# exit from the interface configruaiton mode
tn.write("exit\n")
# exit from the configuraiotn mode
tn.write("exit\n")
# exit from the privilege mode
tn.write("exit\n")
print tn.read_all() # this line is required, but not sure why?
tn.close()
oid = ".1.3.6.1.2.1.4.20.1.1"
snmp = "snmpwalk -v2c -c public %s %s" % (router, oid)
# Verify the output via SNMP
fp = os.popen( snmp )
snmp = fp.read().splitlines() # split the outout into a list of "lines"
flag = 0
for line in snmp:
inline = line.rstrip('\n')
list = inline.split()
ip = list[3] # IP address is the 4th item on the list
if ip == newip:
print "The new IP address (%s) is successfully configured on Serial0/0 of %s" % (ip, router)
flag = 1
break
if flag == 0:
print "failed operation: %s is not configured on Serial0/0 of %s" % (newip, router)
Now when I run the script, i input "python script.py deviceIPaddress newInterfaceIPaddress" this is what i get:
ip address 111.11.111.11 255.255.255.0
^
% Invalid input detected at '^' marker.
Router4(config)#exit
Router4#exit
failed operation: 111.11.111.11 is not configured on Serial0/0 of <device>
Any idea why I'm getting that invalid input error?
Thank you in advanced!
I have a lot of cisco switches and routers in my environment. I have three sets of credentials (only one of them works with a particular device. I then have the IPs listed in a notepad (sub.txt). And the configuration in another notepad (config.txt)
The aim is to push the configurations (line by line) from config.txt to the list of list of IP via SSH. If the command is accepted by the devices, a log should be put into success.txt and if the command is not accepted for some reason, a log should be appended to fail.txt
But this does not work. Can you please help me fix?
import paramiko
import time
import sys
import logging
import socket
import pexpect
import traceback
from pexpect.popen_spawn import PopenSpawn
remote_conn_pre = paramiko.SSHClient()
remote_conn_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ips = [i.strip() for i in open("sub.txt")]
user_local = "user1"
pass_local = "pass1"
user_aspac = "user2"
pass_aspac = "pass2"
user_batcca = "user3"
pass_batcca = "pass3"
g = open('config.txt', 'r+')
str = g.read()
g.close
success = open('success.txt', 'a')
fail = open('failed.txt', 'a')
paramiko.util.log_to_file("paramiko.log")
for ip in ips:
try:
remote_conn_pre.connect(ip, username=user_local, password=pass_local, timeout=4, look_for_keys=False, allow_agent=False)
#print ("SSH connection established to %s" + ip)
remote_conn = remote_conn_pre.invoke_shell()
print (ip + ' === local credential')
#remote_conn.send("show switch\n")
remote_conn.send((str))
time.sleep(2)
output = remote_conn.recv(5000)
print (output)
except paramiko.AuthenticationException:
try:
remote_conn_pre.connect(ip, username=user_aspac, password=pass_aspac, timeout=4, look_for_keys=False, allow_agent=False)
remote_conn1 = remote_conn_pre.invoke_shell()
print ip + ' === Global Credentials'
#output = remote_conn.recv(500)
#remote_conn.send("show switch")
#remote_conn.send("\n")
remote_conn1.send((str))
time.sleep(2)
output1 = remote_conn1.recv(5000)
print (output1)
except paramiko.AuthenticationException:
try:
#remote_conn_pre.connect(ip, username=user_batcca, password=pass_batcca, timeout=4, look_for_keys=False, allow_agent=False)
#remote_conn2 = remote_conn_pre.invoke_shell()
child = pexpect.popen_spawn.PopenSpawn('ssh ' + user_batcca + '#' + ip)
child.expect ('[pP]assword:')
child.sendline(pass_batcca)
print ip + ' === BATCCA Credential'
#output2 = remote_conn2.recv(5000)
for line in open('Config.txt').xreadlines():
child.sendline(line)
i = child.expect (['#', '^'])
if i==0:
success.write(ip + '\t' + line +'\n')
elif i==1:
fail.write(ip + '\t' + line +'\n')
time.sleep(5)
output2 = child.recv(5000)
print (output2)
except paramiko.AuthenticationException:
print ip + ' === Bad credentials'
remote_conn3 = remote_conn_pre.invoke_shell()
output3 = remote_conn3.recv(5000)
print (output3)
except paramiko.SSHException:
print ip + ' === Issues with ssh service'
except socket.error:
print ip + ' === Device unreachable'
I've been editing this port scanner for an information security project.
The code works but throws errors (Pycharm Edu) on lines 63 and 34 in that order.
The error message for line 63 is: 'line 63, in
checkhost(target). I've looked at this and can't see why this would throw an error specifically as it is defined on line 34.
The error message for line 34 is: 'NameError: global name 'conf' is not defined'. It's not clear why this is a problem either.
Any help is much appreciated.
The Python code environment is Python 2.7.10
#! /usr/bin/python
from logging import getLogger, ERROR # Import Logging Things
getLogger("scapy.runtime").setLevel(ERROR) # Get Rid if IPv6 Warning
import scapy
import sys
from datetime import datetime # Other stuff
from time import strftime
try:
target = raw_input("[*] Enter Target IP Address: ")
min_port = raw_input("[*] Enter Minumum Port Number: ")
max_port = raw_input("[*] Enter Maximum Port Number: ")
try:
if int(min_port) >= 0 and int(max_port) >= 0 and
int(max_port) >= int(min_port): # Test for valid range of ports
pass
else: # If range didn't raise error, but didn't meet criteria
print "\n[!] Invalid Range of Ports"
print "[!] Exiting..."
sys.exit(1)
except Exception: # If input range raises an error
print "\n[!] Invalid Range of Ports"
print "[!] Exiting..."
sys.exit(1)
except KeyboardInterrupt: # In case the user wants to quit
print "\n[*] User Requested Shutdown..."
print "[*] Exiting..."
sys.exit(1)
ports = range(int(min_port), int(max_port)+1)
start_clock = datetime.now() # Start clock for scan time
SYNACK = 0x12 # Set flag values for later reference
RSTACK = 0x14
def checkhost(target): # Function to check if target is up
conf.verb = 0 # Hide output
try:
ping = sr1(IP(dst = ip)/ICMP()) # Ping the target
print "\n[*] Target is Up, Beginning Scan..."
except Exception: # If ping fails
print "\n[!] Couldn't Resolve Target"
print "[!] Exiting..."
sys.exit(1)
def scanport(port): # Function to scan a given port
try:
srcport = RandShort() # Generate Port Number
conf.verb = 0 # Hide output
SYNACKpkt = sr1(IP(dst = target)/TCP(sport = srcport,
dport = port,flags = "S"))
pktflags = SYNACKpkt.getlayer(TCP).flags
if pktflags == SYNACK: # Cross reference Flags
return True # If open, return true
else:
return False
RSTpkt = IP(dst = target)/TCP(sport = srcport, dport = port,
flags = "R") # Construct RST packet send(RSTpkt)
except KeyboardInterrupt: # In case the user needs to quit
RSTpkt = IP(dst = target)/TCP(sport = srcport, dport = port,
flags = "R") send(RSTpkt)
print "\n[*] User Requested Shutdown..."
print "[*] Exiting..."
sys.exit(1)
checkhost(ip) # Run checkhost() function from earlier
print "[*] Scanning Started at " + strftime("%H:%M:%S") + "!\n"
for port in ports: # Iterate through range of ports
status = scanport(port) # Feed each port into scanning function
if status == True: # Test result
print "Port " + str(port) + ": Open" # Print status
stop_clock = datetime.now() # Stop clock for scan time
total_time = stop_clock - start_clock # Calculate scan time
print "\n[*] Scanning Finished!" # Confirm scan stop
print "[*] Total Scan Duration: " + str(total_time) # Print scan time
The problem is with your import statement, it should
be:
>>> import scapy
>>> from scapy.all import conf
>>> conf.verb = 0
or even better to get rid of possible similar errors in the future
just import scapy as:
>>> from scapy.all import *
>>> conf.verb = 0
Now it should work fine.
Everyone, hello!
I'm currently trying to use Telnetlib (https://docs.python.org/2/library/telnetlib.html) for Python 2.7 to communicate with some external devices.
I have the basics set up:
import sys
import telnetlib
tn_ip = xxxx
tn_port = xxxx
tn_username = xxxxx
tn_password = xxxx
searchfor = "Specificdata"
def telnet():
try:
tn = telnetlib.Telnet(tn, tn, 15)
tn.set_debuglevel(100)
tn.read_until("login: ")
tn.write(tn_username + "\n")
tn.read_until("Password: ")
tn.write(tn_password + "\n")
tn.read_until(searchfor)
print "Found it!"
except:
print "Unable to connect to Telnet server: " + tn_ip
telnet()
And I'm trying to go through all of the data it's outputting (which is quite a lot) until I catch what I need. Although it is logging in quite fine, and even finds the data I'm looking for, and prints my found it message, I'm trying for a way to keep the connection with telnet open as there might be other data (or repeated data) i would be missing if I logged off and logged back in.
Does anyone know how to do this?
Seems like you want to connect to external device once and print a message each time you see a specific string.
import sys
import telnetlib
tn_ip = "0.0.0.0"
tn_port = "23"
tn_username = "xxxxx"
tn_password = "xxxx"
searchfor = "Specificdata"
def telnet():
try:
tn = telnetlib.Telnet(tn_ip, tn_port, 15)
except:
print "Unable to connect to Telnet server: " + tn_ip
return
tn.set_debuglevel(100)
tn.read_until("login: ")
tn.write(tn_username + "\n")
tn.read_until("Password: ")
tn.write(tn_password + "\n")
while True:
tn.read_until(searchfor)
print "Found it"
telnet()
I wanted to create a Python program that does several things. Ping all addresses in a predefined network, gather the DNS information, write a file with IP address, DNS name, ping fail or pass, date. Then run and email the resulting file to myself once a week, every Friday. I have created this program and will post my own answer. I am new to Python and was able to get this written with the help from other answers posted on this site. Thanks to all those who contributed answers on this site. Hope the answer I post will help someone else.
#!/usr/bin/python3.4
#Above statement makes sure you are using version 3.4
#when multiple versions are installed. has to be the 1st line.
# Import modules
import subprocess
import socket
import errno
import time
import datetime
import ipaddress
today = datetime.date.today()
# define DNS lookup and error handling
# return none,none,none needed otherwise if no DNS record
# the routine errors out and the program stops
def lookup(addr):
try:
return socket.gethostbyaddr(addr)
except socket.herror:
return None, None, None
# Prompt the user to input a network address
# commented out the prompt for input so it can run unattended
# net_addr = input("Enter a network address in CIDR
format(ex.192.168.1.0/24): ")
net_addr = ('192.168.1.0/24')
# Create the network
ip_net = ipaddress.ip_network(net_addr)
# Get all hosts on that network
all_hosts = list(ip_net.hosts())
# Configure subprocess to hide the console window
# removed code due to errors not windows linux
# setup online and offline count variables
offCnt = 0
onCnt = 0
# Open file and or create if it doesn't exist.
# file to be overwritten each time the program is run.
file = open("lab-ip.doc","w")
# For each IP address in the subnet,
# run the ping command with subprocess.popen interface
# Grab the DNS information for each IP address
# Print to console add counters and write to file.
for i in range(len(all_hosts)):
output = subprocess.Popen(['ping', '-c', '2', str(all_hosts[i])],
stdout=subprocess.PIPE).communicate()[0]
name,alias,addresslist = lookup(str(all_hosts[i]))
if "Destination Host Unreachable" in output.decode('utf-8'):
print(str(all_hosts[i]), " Ping Fail", str(name), today)
file.write(str(all_hosts[i]) + " Ping Fail - " + str(name) + " " + str(today) + "\n")
offCnt = offCnt + 1
elif "Request timed out" in output.decode('utf-8'):
print(str(all_hosts[i]), " Ping Fail", str(name), today)
file.write(str(all_hosts[i]) + " Ping Fail - " + str(name) + " " + str(today) + "\n")
offCnt = offCnt + 1
else:
print(str(all_hosts[i]), " Ping Pass", str(name), today)
file.write(str(all_hosts[i]) + " Ping Pass - " + str(name) + " " + str(today) + "\n")
onCnt = onCnt + 1
print ("Pass count = ", str(onCnt))
file.write("Pass count = " + str(onCnt))
print ("Fail count = ", str(offCnt))
file.write(" Fail count = " + str(offCnt))
file.close()
# Import yagmail for the actual sending function
import yagmail
yag = yagmail.SMTP('Gmail-id', 'gmail-pswd')
yag.send('email#email.com', subject = "Lab-ip List",contents = 'lab-ip.doc')
yag.send('email2#email2.com', subject = "Lab-ip List",contents = 'lab-ip.doc')
#end