how to handle socket errors as exceptions in python + paramiko? - python

I want to return an error code when the following error gets raised:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "UserManagementRemote.py", line 202, in create_group
ssh.connect(hostname, username=user, password=remotepass)
File "/usr/lib/python2.6/site-packages/paramiko/client.py", line 290, in connect
sock.connect(addr)
File "<string>", line 1, in connect
socket.error: [Errno 113] No route to host
>>>
But I'm currently having trouble catching the error raised.
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname, username=user, password=remotepass)
except paramiko.AuthenticationException:
return 259
except socket.error:
return 261
chan = ssh.get_transport().open_session()
chan.exec_command(command)
codest = chan.recv_exit_status()
ssh.close()
return codest
Resulting on this:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "UserManagementRemote.py", line 207, in create_group
except socket.error:
NameError: global name 'socket' is not defined
>>>
Any ideas?

Do
import socket
in the module where you do the exception handling.
To prevent this problem in the future, run pyflakes on all your source files. That will catch a lot of other errors as well.

Related

MySQL and Python Connector Test Errors

I am connecting, or trying to, MySQL and Python via PyCharm and I input the code that I was given and I am getting several errors that I am unable to resolve. Is there a pro out there that can assist?
Here is the code:
import mysql.connector
from mysql.connector import errorcode
config = {
"user": "movies_user",
"password": "popcorn",
"host": "127.0.0.1",
"database": "movies",
"raise on warnings": True
}
try:
db = mysql.connector.connect(**config)
print("\n Database user {} connected to MySQL on host {} with database {}".format(config["user"], config["host"],
config["database"]))
input("\n\n Press any key to continue...")
except mysql.connector as Error:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print(" The supplied username or password are invalid")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print(" The supplied database does not exist")
else:
print(err)
finally:
db.close()
And here are the errors:
Traceback (most recent call last):
File "C:\Users\Ryan\PycharmProjects\CSD_310\venv\lib\site-packages\mysql\connector\connection.py", line 353, in config
DEFAULT_CONFIGURATION[key]
KeyError: 'raise on warnings'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Ryan\PycharmProjects\CSD_310\mysql_test.py", line 14, in <module>
db = mysql.connector.connect(**config)
File "C:\Users\Ryan\PycharmProjects\CSD_310\venv\lib\site-packages\mysql\connector\__init__.py", line 159, in connect
return MySQLConnection(*args, **kwargs)
File "C:\Users\Ryan\PycharmProjects\CSD_310\venv\lib\site-packages\mysql\connector\connection.py", line 129, in __init__
self.connect(**kwargs)
File "C:\Users\Ryan\PycharmProjects\CSD_310\venv\lib\site-packages\mysql\connector\connection.py", line 449, in connect
self.config(**kwargs)
File "C:\Users\Ryan\PycharmProjects\CSD_310\venv\lib\site-packages\mysql\connector\connection.py", line 355, in config
raise AttributeError("Unsupported argument '{0}'".format(key))
AttributeError: Unsupported argument 'raise on warnings'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Ryan\PycharmProjects\CSD_310\mysql_test.py", line 20, in <module>
except mysql.connector as Error:
TypeError: catching classes that do not inherit from BaseException is not allowed
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Ryan\PycharmProjects\CSD_310\mysql_test.py", line 30, in <module>
db.close()
NameError: name 'db' is not defined
Process finished with exit code 1
I feel like I have tried everything that I can possibly find on Google. Any help is much appreciated!
I have tried the above code and I have tried resolving the errors to no avail.

How to run a program in Paramiko's SSH ProxyCommand

I'm pretty new with Paramiko and python in general. I'm trying to connect to a server and execute some commands on it by ssh through the use of Paramiko's API and a program called Pomerium. My ssh config file is as shown below
Host *.stg-id-proxy.lab.com
ProxyCommand pomerium-cli tcp --listen - %h:%p
User placeholder
and my python code in file "ssh4.py" is as follows
import paramiko
host = "place.stg-id-proxy.lab.com"
port = 22
username = "placeholder"
password = "pass#!#"
command = "pwd"
proxy = paramiko.ProxyCommand("pomerium-cli tcp --listen - %h:%p")
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, port, username, password, allow_agent=False, look_for_keys=False, sock=proxy, banner_timeout=60)
stdin, stdout, stderr = ssh.exec_command(command)
lines = stdout.readlines()
print(lines)
but when I tried running:
python3 ssh4.py
I keep getting the following error
Exception (client): Error reading SSH protocol banner
Traceback (most recent call last):
File "/Users/placeholder/Library/Python/3.8/lib/python/site-packages/paramiko/transport.py", line 2271, in _check_banner
buf = self.packetizer.readline(timeout)
File "/Users/placeholder/Library/Python/3.8/lib/python/site-packages/paramiko/packet.py", line 380, in readline
buf += self._read_timeout(timeout)
File "/Users/placeholder/Library/Python/3.8/lib/python/site-packages/paramiko/packet.py", line 622, in _read_timeout
raise socket.timeout()
socket.timeout
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/placeholder/Library/Python/3.8/lib/python/site-packages/paramiko/transport.py", line 2094, in run
self._check_banner()
File "/Users/placeholder/Library/Python/3.8/lib/python/site-packages/paramiko/transport.py", line 2275, in _check_banner
raise SSHException(
paramiko.ssh_exception.SSHException: Error reading SSH protocol banner
Traceback (most recent call last):
File "/Users/placeholder/Library/Python/3.8/lib/python/site-packages/paramiko/transport.py", line 2271, in _check_banner
buf = self.packetizer.readline(timeout)
File "/Users/placeholder/Library/Python/3.8/lib/python/site-packages/paramiko/packet.py", line 380, in readline
buf += self._read_timeout(timeout)
File "/Users/placeholder/Library/Python/3.8/lib/python/site-packages/paramiko/packet.py", line 622, in _read_timeout
raise socket.timeout()
socket.timeout
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "ssh4.py", line 11, in <module>
ssh.connect(host, port, username, password, allow_agent=False, look_for_keys=False, sock=proxy, banner_timeout=60)
File "/Users/placeholder/Library/Python/3.8/lib/python/site-packages/paramiko/client.py", line 406, in connect
t.start_client(timeout=timeout)
File "/Users/placeholder/Library/Python/3.8/lib/python/site-packages/paramiko/transport.py", line 699, in start_client
raise e
File "/Users/placeholder/Library/Python/3.8/lib/python/site-packages/paramiko/transport.py", line 2094, in run
self._check_banner()
File "/Users/placeholder/Library/Python/3.8/lib/python/site-packages/paramiko/transport.py", line 2275, in _check_banner
raise SSHException(
paramiko.ssh_exception.SSHException: Error reading SSH protocol banner
So, any help would be appreciated. Also documentation for Pomerium can be found here:
https://github.com/pomerium/cli
Thank you in advance.

How to send an error message being printed in an exception case by email to a user?

I am using Python3.7
I am trying to email an error in the except condition to the user if the code is not working and following is my code:
except Exception as e:
logging.basicConfig(filename='logfile.log',format='%(asctime)s %(message)s',filemode='w')
logger=logging.getLogger()
logger.setLevel(logging.ERROR)
logger.error(e)
print("ERROR MESSAGE",e)
MY_ADDRESS = '*****#gmail.com'
PASSWORD = '*******'
MY_ADDRESS1 = '****#gmail.com'
s = smtplib.SMTP(host='smtp.gmail.com', port=***)
s.starttls()
s.login(MY_ADDRESS, PASSWORD)
print("login")
msg = MIMEMultipart() # create a message
msg['From']=MY_ADDRESS
msg['To']=MY_ADDRESS1
msg['Subject']="ERROR MESSAGE"
message="ERROR"
msg.attach.as_string(MIMEText(e))
print("ERROR MAILED")
s.send_message(msg)
s.quit()
I want to send the error message in variable 'e' which is being printed
But I am unable to do so
Following is the error:
This is the error which i want to print and mail:
ERROR MESSAGE [Errno 2] No such file or directory: 'C:\\Python37\\Processed\\Invoice.xlsx'
This is the error shown on the python shell:
Traceback (most recent call last):
File "C:\Python37\Sopan.py", line 30, in <module>
wb.save(workbook_name)
File "C:\Python37\lib\site-packages\openpyxl\workbook\workbook.py", line 408, in save
save_workbook(self, filename)
File "C:\Python37\lib\site-packages\openpyxl\writer\excel.py", line 291, in save_workbook
archive = ZipFile(filename, 'w', ZIP_DEFLATED, allowZip64=True)
File "C:\Python37\lib\zipfile.py", line 1207, in __init__
self.fp = io.open(file, filemode)
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Python37\\Processed\\Invoice.xlsx'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Python37\Sopan.py", line 88, in <module>
msg.attach.as_string(MIMEText(e))
AttributeError: 'function' object has no attribute 'as_string'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Python37\Sopan.py", line 88, in <module>
msg.attach.as_string(MIMEText(e))
AttributeError: 'function' object has no attribute 'as_string'
How do i send the error message being printed in variable 'e' by email to someone
THANK YOU
The logging module itself has smtp handler you can do something like this:
import logging
import logging.handlers
smtp_handler = logging.handlers.SMTPHandler(mailhost=("smtp.example.com", 25),
fromaddr="someone#something.com",
toaddrs="receiver#mail.com",
subject=u"ERROR IN YOURAPP!")
logger = logging.getLogger()
logger.addHandler(smtp_handler)
try:
raise Exception
except Exception as e:
logger.exception('Unhandled Exception')
for more info see doc

How to handle errors: Pyntc ssh to network device

I am new to network automation, and trying to use pyntc to ssh to the device. I am not sure how to write the code correctly to handle the ssh timeout or authentication error, etc.
My code is as below:
from pyntc import ntc_device as NTC
from pyntc_devices_list import Get_Devices_List
all_devices = Get_Devices_List()
for device in all_devices:
print('Backing up ' + device['name'])
DEVICE = NTC(host=device['ip'], username=device['username'], password=device['password'], device_type='cisco_ios$
try:
DEVICE.open()
except Exception:
print('Error')
continue
back_config = DEVICE.backup_running_config(device['name'] + '.cfg')
DEVICE.close()
I manually turned off this device, and then I found python code was quit:
root#Network-Automation:~/Pyntc# python3 pyntc_error_handling.py
Backing up ESW1
Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/netmiko/base_connection.py", line 884, in establish_connection
self.remote_conn_pre.connect(**ssh_connect_params)
File "/usr/local/lib/python3.5/dist-packages/paramiko/client.py", line 368, in connect
raise NoValidConnectionsError(errors)
paramiko.ssh_exception.NoValidConnectionsError: [Errno None] Unable to connect to port 22 on 192.168.122.72
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "pyntc_error_handling.py", line 8, in <module>
DEVICE = NTC(host=device['ip'], username=device['username'], password=device['password'], device_type='cisco_ios_ssh')
File "/usr/local/lib/python3.5/dist-packages/pyntc/__init__.py", line 38, in ntc_device
return device_class(*args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/pyntc/devices/ios_device.py", line 42, in __init__
self.open()
File "/usr/local/lib/python3.5/dist-packages/pyntc/devices/ios_device.py", line 300, in open
verbose=False,
File "/usr/local/lib/python3.5/dist-packages/netmiko/ssh_dispatcher.py", line 246, in ConnectHandler
return ConnectionClass(*args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/netmiko/base_connection.py", line 317, in __init__
self._open()
File "/usr/local/lib/python3.5/dist-packages/netmiko/base_connection.py", line 322, in _open
self.establish_connection()
File "/usr/local/lib/python3.5/dist-packages/netmiko/base_connection.py", line 890, in establish_connection
raise NetMikoTimeoutException(msg)
netmiko.ssh_exception.NetMikoTimeoutException: Connection to device timed-out: cisco_ios 192.168.122.72:22
Looks like there are more than 1 errors ...
You are doing a minor mistake here, you are expecting an error than trying to same the output. In case of error, the script will through an error. Try it this way.
from pyntc import ntc_device as NTC
from pyntc_devices_list import Get_Devices_List
all_devices = Get_Devices_List()
try:
for device in all_devices:
print('Backing up ' + device['name'])
DEVICE = NTC(host=device['ip'], username=device['username'], password=device['password'], device_type='cisco_ios')
DEVICE.open()
back_config = DEVICE.backup_running_config(device['name'] + '.cfg')
DEVICE.close()
except Exception as Err:
print(Err)

Python determine if HTTPConnection failed to connect

In Python, how I can determine if HTTPConnection failed to connect to server, for example, by bad server address?
import httplib
import sys
if len(sys.argv) != 2:
print 'Usage: server'
quit()
con = httplib.HTTPConnection(argv[1]) # how I can determine if this fails?
Try this after instantiating the object con.connect().
If the connection is unable to be made, this call will throw an exception.
Example:
>>> import httplib
>>> con = httplib.HTTPConnection('127.0.0.1')
>>> con.connect()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/httplib.py", line 772, in connect
self.timeout, self.source_address)
File "/usr/lib/python2.7/socket.py", line 571, in create_connection
raise err
socket.error: [Errno 111] Connection refused
You could try adding try() and except() statements.

Categories