python ssh paramiko save to file - python

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.

Related

How do I allow a client to connect to python server?

When I run the server, then the client, I Automatically get these messages:
**SERVER: **
Traceback (most recent call last):
File "C:\Users\Ryan\Desktop\testproj-server.py", line 142, in
handleConnectedSocket()
File "C:\Users\Ryan\Desktop\testproj-server.py", line 58, in handleConnectedSocket
rcvdStr = rcvdStr + fd.recv(1024)
TypeError: can only concatenate str (not "bytes") to str
**CLIENT: **
ERROR: Cannot connect to chat server [WinError 10056] A connect request was made on an already connected socket
Exiting... Goodbye! *
This is my code:
SERVER CODE:
import socket
import select
def runSelect():
selectUnsuccessful = True
while selectUnsuccessful:
try:
readyRecvList, readySendList, readyErrList = select.select(recvList, sendList, [])
selectUnsuccessful = False
except select.error:
for fd in recvList:
try:
tempRecvList, tempSendList, tempErrList = select.select([fd], [], [], 0)
except select.error:
if fd == serverSocket:
fd.close()
exit(1)
else:
if fd in recvList:
recvList.remove(fd)
fd.close()
return readyRecvList, readySendList
def handleListeningSocket():
try:
newConnectionSocket, addr = serverSocket.accept()
except socket.error as err:
print("\nERROR: Something went wrong in the accept() function call:", err)
exit(1)
try:
recvList.append(newConnectionSocket)
sendList.append(newConnectionSocket)
print("INFO: Connecting socket created between %s and %s" %
(newConnectionSocket.getsockname(), newConnectionSocket.getpeername()))
print("* Client %s is ready to chat *" % (str(newConnectionSocket.getpeername())))
except (socket.error, socket.gaierror) as err:
print("\nERROR: Something went wrong with the new connection socket:", err)
if newConnectionSocket in recvList:
recvList.remove(newConnectionSocket)
sendList.remove(newConnectionSocket)
newConnectionSocket.close()
def handleConnectedSocket():
try:
recvIsComplete = False
rcvdStr = ""
while not recvIsComplete:
rcvdStr = rcvdStr + fd.recv(1024)
if fd not in sendList:
sendList.append(fd)
# ~ is the delimiter used to indicate message start and finish
if rcvdStr.strip('~') != "":
if (rcvdStr[0] == "~") and (rcvdStr[-1] == "~"):
recvIsComplete = True
clientMessage = rcvdStr.strip('~')
else: # if empty string, connection has been terminated
if fd in recvList:
recvList.remove(fd)
if fd in sendList:
sendList.remove(fd)
del clientMessages[fd] # Delete connection information
fd.close()
if clientMessage == "quit()":
print ("\n* Client %s has left the chat room *\n" % (str(fd.getpeername())))
if fd in recvList:
recvList.remove(fd)
fd.close()
if fd in sendList:
sendList.remove(fd)
fd.close()
else:
print("\n%s: %s" % (fd.getpeername(), clientMessage))
# add message to dictionary, pending transmission
clientMessages[fd] = str(clientMessage)
except socket.error as err:
print("\nERROR: Connection to the client has abruptly ended:", err)
if fd in recvList:
recvList.remove(fd)
if fd in sendList:
sendList.remove(fd)
fd.close()
print("* I am ready to chat with a new client! *\n")
"""
main - Runs the Full Duplex Chat server
"""
# Global Variables
serverHost = 'localhost'
serverPort = 22222
recvList = []
sendList = []
clientMessages = {}
try:
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serverSocket.setblocking(0)
serverSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
serverSocket.bind((serverHost, serverPort))
serverSocket.listen(3)
print ("INFO: I am listening at %s" % (str(serverSocket.getsockname())))
print ("* I am ready to chat with a new client! *\n")
except (socket.error, socket.gaierror) as err:
print ("\nERROR: Something went wrong in creating the listening socket:", err)
exit(1)
recvList = [serverSocket]
try:
while True:
serverSocket.setblocking(False)
readyForRecv, readyForSend = runSelect()
for fd in readyForRecv:
if fd == serverSocket:
handleListeningSocket()
else:
handleConnectedSocket()
for fd in readyForSend:
try:
if fd in clientMessages.keys(): # See if connection information exists
broadcast = str(clientMessages[fd]) # Add message to broadcast variable
if broadcast: # See if a message is actually there
for client in readyForSend: # Broadcast message to every connected client
if broadcast != "":
print ("* Broadcasting message \"%s\" to %s *" % (str(broadcast), client.getpeername()))
client.send(str(fd.getpeername()) + ": " + str(broadcast))
clientMessages[fd] = "" # Empty pending messages
#except:
# print "\nERROR: Something awful happened while broadcasting messages"
#break
except socket.error as err:
print ("\nERROR: Something awful happened with a connected socket:", err)
if fd in recvList:
recvList.remove(fd)
if fd in sendList:
sendList.remove(fd)
fd.close()
except KeyboardInterrupt:
for fd in recvList:
fd.close()
for fd in sendList:
fd.close()
print ("\nINFO: KeyboardInterrupt")
print ("* Closing all sockets and exiting... Goodbye! *")
exit(0)
CLIENT CODE:
import socket
import select
import sys
def main():
serverHost = 'localhost'
serverPort = 22222
try:
clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error as err:
print("ERROR: Cannot create client side socket:", err)
exit(1)
while True:
try:
clientSocket.connect((serverHost, serverPort))
except socket.error as err:
print("ERROR: Cannot connect to chat server", err)
print("* Exiting... Goodbye! *")
exit(1)
except:
print("ERROR: Something awful happened!")
exit(1)
break
recvList = [clientSocket, sys.stdin]
print("* You are now connected to chat server %s as %s *" %
(clientSocket.getpeername(), clientSocket.getsockname()))
try:
while True:
readyRecvList, readySendList, readyErrList = select.select(recvList, [], [])
for fd in readyRecvList:
if fd == sys.stdin:
message = sys.stdin.readline().rstrip()
clientSocket.sendall("~" + str(message) + "~")
if (message == "quit()"):
print("* Exiting chat room! *")
clientSocket.close()
exit(0)
break
elif fd == clientSocket:
clientSocket.settimeout(3)
try:
message = clientSocket.recv(2048)
except socket.timeout as err:
print("ERROR: The recv() function timed out after 3 seconds! Try again.")
except:
print("ERROR: Something awful happened!")
else:
if message == "":
break
else:
print("%s\n" % (message))
clientSocket.settimeout(None)
break
except select.error as err:
for fd in recvList:
try:
tempRecvList, tempSendList, tempErrList = select.select([fd], [], [], 0)
except select.error:
if fd == clientSocket:
fd.close()
exit(1)
else:
if fd in recvList:
recvList.remove(fd)
fd.close()
except socket.error as err:
print("ERROR: Cannot connect to chat server", err)
print("* Exiting... Goodbye! *")
exit(1)
if fd in recvList:
fd.close()
except KeyboardInterrupt:
print("\nINFO: KeyboardInterrupt")
print("* Closing all sockets and exiting chat server... Goodbye! *")
clientSocket.close()
exit(0)
if __name__ == '__main__':
main()
You didn't decode the received bytes
rcvdStr = rcvdStr + fd.recv(1024).decode()
I haven't exactly checked, so tell me if this helps
EDIT:
Ok so for starters remove the while statement in line 17 of the client, once the client is connected to the server you can't connect again (make sure you remove the break in the new line 26)
The new line 34 is causinf errors (readyRecvList, readySendList, readyErrList = select.select(recvList, [], []))
Traceback (most recent call last):
File "C:\Users\User\Desktop\Client.py", line 93, in <module>
main()
File "C:\Users\User\Desktop\Client.py", line 34, in main
readyRecvList, readySendList, readyErrList = select.select(recvList, [], [])
io.UnsupportedOperation: fileno

Paramiko - SSH to remote host

I have a server:
import threading
import paramiko
import subprocess
import sys
import socket
host_key = paramiko.RSAKey(filename='test_rsa.key')
class Server(paramiko.ServerInterface):
def _init_(self):
self.event = threading.Event()
def check_channel_request(self, kind, chanid):
if kind == 'session':
return paramiko.OPEN_SUCCEEDED
return paramiko.OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED
def check_auth_password(self, username, password):
if(username=='justin') and (password == 'lovesthepython'):
return paramiko.AUTH_SUCCESSFUL
return paramiko.AUTH_FAILED
server = sys.argv[1]
ssh_port = int(sys.argv[2])
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((server, ssh_port))
sock.listen(100)
print '[+] Listening for connection ...'
client, addr = sock.accept()
except Exception, e:
print '[-] Listen failed: ' + str(e)
sys.exit(1)
print '[+] Got a connection!'
try:
bhSession = paramiko.Transport(client)
bhSession.add_server_key(host_key)
server = Server()
try:
bhSession.start_server(server=server)
except paramiko.SSHException, x:
print '[-] SSH Negotiation Failed'
chan = bhSession.accept(20)
print '[+] Authenticated!'
print chan.recv(1024)
chan.send('Welcome to bh_ssh')
while True:
try:
command= raw_input("Enter command: ").strip('\n')
if command != 'exit':
chan.send(command)
print chan.recv(1024) + '\n'
else:
chan.send('exit')
print 'exiting'
bhSession.close()
raise Exception ('exit')
except KeyboardInterrupt:
bhSession.close()
except Exception, e:
print '[-] Caught exception: ' + str(e)
try:
bhSession.close()
except:
pass
sys.exit(1)
My code to connect to this is:
import threading
import paramiko
import subprocess
def ssh_command(ip, port, user, passwd, command):
client = paramiko.SSHClient()
#client.load_host_keys('/home/justin/.ssh/known_hosts')
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(ip, port, username=user, password=passwd)
ssh_session = client.get_transport().open_session()
if ssh_session.active:
ssh_session.send(command)
print ssh_session.recv(1024)
while True:
command = ssh_session.recv(1024)
try:
cmd_output = subprocess.check_output(command, shell=True)
ssh_session.send(cmd_output)
except Exception,e:
ssh_session.send(str(e))
client.close()
return
ssh_command('IP_ADDRESS_HERE',PORT_HERE,'justin','lovesthepython','id')
When I try to use these on separate PCs and use public IP addresses it won't connect. The server I bind to 0.0.0.0 and then use the public IP address of the server's computer to the client code. I imagine I am doing something fairly obvious wrong. If anyone can help, it would be very much appreciated.

Python - Warning: Unexpected Error: <class 'IndexError'>

I am trying to use some code to read username and password from a file called ".logon" and establish a connection to redshift. But I got the error message "Python - Warning: Unexpected Error: ".
Here is my code:
def redshift_connect():
try:
l_user = getpass.getuser()
home = expanduser("~")
f = open(home + '/.logon')
logline = f.readline()
usr = logline.split(',')[0].split('/')[1].strip()
pwd = logline.split(',')[1].rstrip()
conn=psycopg2.connect(host='host-name',
port= 5439, user= usr, password= pwd)
return conn
except IOError as e:
print ('I/O error ({0}): {1}: .tdlogon missing!!'.format(e.errno, e.strerror))
except:
print ('Warning: Unexpected Error:',sys.exc_info()[0])
else:
raise ConnectionError('Cannot establish connectionw with Redshift.')
I guess the expression logline.split(',') works and returns an array with only one entry. The expression logline.split(',')[1] then raises an IndexError which you catch in the unspecific except clause.

parallel files download from ftp

When i try to download files from ftp sequentially it works perfectly
import ftplib
import os
import logging
class pyFTPDownload(object):
def __init__(self,
remote_host=None,
port=None,
username=None,
passwd=None,
input_folder=None,
output_folder=None,
ftp_conn_id=None,
timeout=10
):
super(pyFTPDownload, self).__init__()
self.remote_host = remote_host
self.port = port
self.username = username
self.passwd = passwd
self.input_folder = input_folder
self.output_folder = output_folder
self.ftp_conn_id = ftp_conn_id
self.timeout = timeout
self.client = None
def get_conn(self):
if not self.client:
logging.info('creating ftp client for conn_id: {0}'.format(self.ftp_conn_id))
if not self.username:
raise Exception("Missing required param: username")
if not self.passwd:
raise Exception("Missing required param: passwd")
if not self.remote_host:
raise Exception("Missing required param: remote_host")
if not self.ftp_conn_id:
self.ftp_conn_id = str(self.username) + '#' + str(self.remote_host) + ":" + (
str(self.port) if self.port else "")
try:
client = ftplib.FTP()
client.connect(self.remote_host, (self.port if not self.port else None))
client.login(self.username, self.passwd)
self.client = client
except ftplib.all_errors as remote_host_error:
logging.error("Auth failed while connecting to host: {0}, error: {1}"
.format(self.remote_host, remote_host_error))
except Exception as error:
logging.error("Error connecting to host: {0}, error: {1}"
.format(self.remote_host, error))
return self.client
def get_file(self, input_folder, output_folder=None,file_ext=None,thread_nbr=1):
#os.chdir(output_folder)
ftp = self.get_conn()
#print ftp.dir(input_folder)
logging.debug(input_folder)
if not os.path.exists(input_folder):
try:
os.makedirs(output_folder, 0755)
logging.debug("{0} is created".format(output_folder))
except OSError, e:
logging.error("ERROR: {0}".format(e))
logging.info(output_folder)
ftp.cwd(input_folder)
for filename in ftp.nlst(file_ext): # Loop - looking for matching files
try:
logging.debug("filename {0}".format(filename))
local_file=os.path.join(output_folder,filename)
logging.debug("local_file {0}".format(local_file))
with open(local_file, 'wb') as fhandle:
logging.debug('Getting ' + filename) # for confort sake, shows the file that's being retrieved
ftp.retrbinary('RETR ' + filename, fhandle.write)
fhandle.close()
except Exception as e:
logging.error("could not download file:{0}, terminated with error {1}".format(filename,e))
But when i tried to do the same thing in parallel i get
[Errno 9] Bad file descriptor
or when i try to decomment the following two lines
xftp.connect(self.remote_host,self.port)
xftp.login(self.username,self.passwd)
i get this error: a float is required. But without a stacktrace so i can debug it
my full code follow:
# coding=utf-8
from itertools import izip, repeat
import ftplib
import os
import multiprocessing
from pathos.multiprocessing import ProcessingPool as Pool
import logging
import traceback
class pyFTPDownload(object):
def __init__(self,
remote_host,
port,
username,
passwd,
ftp_conn_id=None
):
super(pyFTPDownload, self).__init__()
self.remote_host = remote_host
self.port = port
self.username = username
self.passwd = passwd
self.ftp_conn_id = ftp_conn_id
self.client = None
if not self.client:
logging.info('creating ftp client for conn_id: {0}'.format(self.ftp_conn_id))
if not self.username:
raise Exception("Missing required param: username")
if not self.passwd:
raise Exception("Missing required param: passwd")
if not self.remote_host:
raise Exception("Missing required param: remote_host")
if not self.ftp_conn_id:
self.ftp_conn_id = str(self.username) + '#' + str(self.remote_host) + ":" + (
str(self.port) if self.port else "")
try:
client = ftplib.FTP()
client.connect(self.remote_host, (self.port if self.port else None))
client.login(self.username, self.passwd)
self.client = client
except ftplib.all_errors as remote_host_error:
logging.error("Auth failed while connecting to host: {0}, error: {1}"
.format(self.remote_host, remote_host_error))
except Exception as error:
logging.error("Error connecting to host: {0}, error: {1}"
.format(self.remote_host, error))
def get_conn(self):
return self.client
class loadData(pyFTPDownload):
def __init__(self,
remote_host,
port,
username,
passwd,
input_folder,
output_folder,
file_ext=None,
nbr_processes=None,
ftp_conn_id = None):
super(loadData, self).__init__(remote_host,port,username,passwd)
self.input_folder=input_folder
self.output_folder=output_folder
self.file_ext=file_ext
self.nbr_processes=nbr_processes
if not input_folder:
raise Exception("Missing required params: input_folder")
if not output_folder:
raise Exception("Missing required params: output_folder")
if not file_ext:
logging.warn("All the existing files in {0} will be considered".format(input_folder))
if not nbr_processes:
logging.warn("The number of processes to be started will be set to {0}".format(Pool.ncpus))
self.nbr_processes=multiprocessing.cpu_count()
def downloadfunc(self,a):
return self.downloadf(*a)
def downloadf(self, inputf, filename, outputf):
global xftp
global local_file
global fhandle
print filename
try:
xftp = self.get_conn()
xftp.connect(self.remote_host,self.port)
xftp.login(self.username,self.passwd)
print xftp
except ftplib.all_errors as remote_host_error:
logging.error("Auth failed while connecting to host: {0}, error: {1}"
.format(self.remote_host, remote_host_error))
except Exception as error:
logging.error("Error connecting to host: {0}, error: {1}"
.format(self.remote_host, error))
try:
logging.debug("filename {0}".format(filename))
local_file = os.path.join(outputf, filename)
logging.debug("local_file {0}".format(local_file))
except Exception as sd:
logging.error("Unkmown error: {}".format(sd))
xftp.cwd(inputf)
try:
with open(local_file, 'wb') as fhandle:
logging.debug('Getting ' + filename) # for confort sake, shows the file that's being retrieved
xftp.retrbinary('RETR ' + filename, fhandle.write)
fhandle.close()
except Exception as k:
logging.error("Could not download {0} : {1}".format(local_file,k))
finally:
xftp.quit()
print traceback
def get_file(self):
print "PREPARING FILE DOWNLOAD"
print self.output_folder
if not os.path.exists(self.output_folder):
try:
logging.debug("{} does not exists".format(self.output_folder))
os.makedirs(self.output_folder,0755)
logging.debug("{0} is created".format(self.output_folder))
except OSError, e:
logging.error("ERROR:{0} could not be created {1}, {2}".format(self.output_folder,e,OSError))
except Exception as d:
logging.error(d)
ftpObj=self.get_conn()
ftpObj.cwd(self.input_folder)
files_to_dl=ftpObj.nlst(self.file_ext)
p = Pool(self.nbr_processes)
try:
p.map(self.downloadfunc, izip(repeat(self.input_folder),files_to_dl,repeat(self.output_folder)))
p.close()
p.join()
except Exception as f:
logging.error(f)
I do not have a lot of experience with python, so it would be very nice of you to check my code.
I have also some questions what is the best way to implement multiprocessing in this case?
I have found the problem with my code.
In the downloadf function and exactly in this code part
try:
xftp = self.get_conn()
xftp.connect(self.remote_host,self.port)
xftp.login(self.username,self.passwd)
print xftp
except ftplib.all_errors as remote_host_error:
logging.error("Auth failed while connecting to host: {0}, error: {1}"
.format(self.remote_host, remote_host_error))
except Exception as error:
logging.error("Error connecting to host: {0}, error: {1}"
.format(self.remote_host, error))
The problem was that i used the same ftp connection instance through, xftp = self.get_conn() and that is why i got errors that didn't seem to describe the source problem, how matter what changes did i introduce to my code to fix that.
The solution is to instantiate a new ftp connection for each process, so instead of the above line of code i do the folloying now: xftp = ftplib.FTP()
Maybe there is a kind soul that could bring a more 'pythonic' explanation to this issue. I would be gratefull

Not able to ignore socket.timeout error using Paramiko

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!

Categories