How to handle errors: Pyntc ssh to network device - python

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)

Related

pymongo: Resolver configuration could not be read or specified no nameservers

It's my first time using MongoDB but I can't seem to fix this one issue, my friend who uses MongoDB doesn't know how to use python so he can't really help me.
Here's my code:
import pymongo
# Replace the uri string with your MongoDB deployment's connection string.
conn_str = "mongodb+srv://sqdnoises:{mypass}#sqd.d4kjb.mongodb.net/myFirstDatabase?retryWrites=true&w=majority"
# set a 5-second connection timeout
client = pymongo.MongoClient(conn_str, serverSelectionTimeoutMS=5000)
try:
print(client.server_info())
print('\n\n\n aka connected')
except Exception:
print("Unable to connect to the server.")
Where {mypass} is my MongoDB password.
I keep getting this error:
Traceback (most recent call last):
File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/dns/resolver.py", line 782, in read_resolv_conf
f = stack.enter_context(open(f))
FileNotFoundError: [Errno 2] No such file or directory: '/etc/resolv.conf'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/pymongo/srv_resolver.py", line 88, in _resolve_uri
results = _resolve('_' + self.__srv + '._tcp.' + self.__fqdn,
File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/pymongo/srv_resolver.py", line 41, in _resolve
return resolver.resolve(*args, **kwargs)
File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/dns/resolver.py", line 1305, in resolve
return get_default_resolver().resolve(qname, rdtype, rdclass, tcp, source,
File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/dns/resolver.py", line 1278, in get_default_resolver
reset_default_resolver()
File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/dns/resolver.py", line 1290, in reset_default_resolver
default_resolver = Resolver()
File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/dns/resolver.py", line 734, in __init__
self.read_resolv_conf(filename)
File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/dns/resolver.py", line 785, in read_resolv_conf
raise NoResolverConfiguration
dns.resolver.NoResolverConfiguration: Resolver configuration could not be read or specified no nameservers.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/storage/emulated/0/! workspace/mongolearn/main.py", line 7, in <module>
client = pymongo.MongoClient(conn_str, serverSelectionTimeoutMS=5000)
File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/pymongo/mongo_client.py", line 677, in __init__
res = uri_parser.parse_uri(
File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/pymongo/uri_parser.py", line 532, in parse_uri
nodes = dns_resolver.get_hosts()
File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/pymongo/srv_resolver.py", line 119, in get_hosts
_, nodes = self._get_srv_response_and_hosts(True)
File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/pymongo/srv_resolver.py", line 99, in _get_srv_response_and_hosts
results = self._resolve_uri(encapsulate_errors)
File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/pymongo/srv_resolver.py", line 95, in _resolve_uri
raise ConfigurationError(str(exc))
pymongo.errors.ConfigurationError: Resolver configuration could not be read or specified no nameservers.
How do I fix this?
I am following https://docs.mongodb.com/drivers/pymongo/
indeed, the problem is that dnspython tries to open /etc/resolv.conf
import dns.resolver
dns.resolver.default_resolver=dns.resolver.Resolver(configure=False)
dns.resolver.default_resolver.nameservers=['8.8.8.8']
Just adde this code to the top of your main code, and that should be sufficient to get you past this hurdle..

How can I get this function to run?

I am trying to run my python code, but the second function(see below.. md5()) does not work! Is this an error that I need to resolve?
**Connecting to device" 10.0.100.126 which image would you like to upload?yes
what would you like to name the image?testing
press enter to continue
Destination filename [testing]? UPLOADING.....................................
from netmiko import ConnectHandler
from rashhad import yml
from keyboard import press
import time
from pynput.keyboard import Key, Controller
from test import image_name
with open('dev_devices.txt') as f:
devices_list = f.read().splitlines()
for ip_address in devices_list:
print('___________________________________________________________\n')
print('Connecting to device" ' + ip_address)
ios_device = {
'device_type': 'cisco_ios',
'ip': ip_address,
'global_delay_factor': 4,
"fast_cli": False,
}
ios_device.update(yml('pass.yml', 'admin_a'))
cmd = "copy tftp://10.36.50.60/s2t54-ipservicesk9-mz.SPA.152-1.SY6.bin bootdisk:/"
def upload():
net_connect = ConnectHandler(**ios_device)
net_connect.enable()
firmware = input("which image would you like to upload?")
if firmware == "yes":
name = input("what would you like to name the image?")
output = net_connect.send_command(cmd + name, delay_factor=4, expect_string=r'Destination filename')
input("press enter to continue")
press('enter')
print(output)
print("UPLOADING.....................................")
net_connect.send_command("wr")
net_connect.disconnect()
upload()
time.sleep(20)
def md5(): # This function does not run for some reason, I have no idea
net_connect = ConnectHandler(**ios_device)
net_connect.enable()
name = input("which image would you like to compare?")
checksum = net_connect.send_command("verify /md5 bootdisk:" + name, delay_factor=4)
print(checksum[-31:])
net_connect.disconnect()
md5()
Errors are below
Destination filename [testing]?
UPLOADING.....................................
Traceback (most recent call last):
File "C:\Users\rashhad.miah\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\paramiko\channel.py", line 699, in recv
out = self.in_buffer.read(nbytes, self.timeout)
File "C:\Users\rashhad.miah\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\paramiko\buffered_pipe.py", line 164, in read
raise PipeTimeout()
paramiko.buffered_pipe.PipeTimeout
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\rashhad.miah\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\netmiko\base_connection.py", line 569, in _read_channel_expect
new_data = self.remote_conn.recv(MAX_BUFFER)
File "C:\Users\rashhad.miah\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\paramiko\channel.py", line 701, in recv
raise socket.timeout()
socket.timeout
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\rashhad.miah\Desktop\netauto\test.py", line 41, in <module>
upload()
File "C:\Users\rashhad.miah\Desktop\netauto\test.py", line 37, in upload
net_connect.send_command("wr")
File "C:\Users\rashhad.miah\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\netmiko\utilities.py", line 430, in wrapper_decorator
return func(self, *args, **kwargs)
File "C:\Users\rashhad.miah\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\netmiko\base_connection.py", line 1490, in send_command
new_data = self.read_until_pattern(pattern=re.escape(cmd))
File "C:\Users\rashhad.miah\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\netmiko\base_connection.py", line 651, in read_until_pattern
return self._read_channel_expect(*args, **kwargs)
File "C:\Users\rashhad.miah\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\netmiko\base_connection.py", line 579, in _read_channel_expect
raise NetmikoTimeoutException(
netmiko.ssh_exception.NetmikoTimeoutException: Timed-out reading channel, data not available.
Process finished with exit code 1
Your exception stack trace indicates that it is failing on your wr execution in the upload function.
File "C:\Users\rashhad.miah\Desktop\netauto\test.py", line 37, in upload
net_connect.send_command("wr")
Do you even need that?
In particular it failed on the echo of that wr command i.e. Netmiko was expecting wr to be echoed and it never saw it:
packages\netmiko\base_connection.py", line 1490, in send_command
new_data = self.read_until_pattern(pattern=re.escape(cmd))
You might want to look at the Netmiko session_log or Netmiko's debug log

How to fetch sizes of all SFTP files in a directory through Paramiko

import paramiko
from socket import error as socket_error
import os
server =['10.10.0.1','10.10.0.2']
path='/home/test/'
for hostname in server:
try:
ssh_remote =paramiko.SSHClient()
ssh_remote.set_missing_host_key_policy(paramiko.AutoAddPolicy())
privatekeyfile = os.path.expanduser('~/.ssh/id')
mykey = paramiko.RSAKey.from_private_key_file(privatekeyfile, password='test123')
ssh_remote.connect(hostname, username = 'test1', pkey = mykey)
sftp=ssh_remote.open_sftp()
for i in sftp.listdir(path):
info = sftp.stat(i)
print info.st_size
except paramiko.SSHException as sshException:
print "Unable to establish SSH connection:{0}".format(hostname)
except socket_error as socket_err:
print "Unable to connect connection refused"
This is my code. I tried to get file size of remote server files. But below error was throwing. Can some please guide on this?
Error
Traceback (most recent call last):
File "<stdin>", line 15, in <module>
File "/usr/lib/python2.6/site-packages/paramiko/sftp_client.py", line 337, in stat
t, msg = self._request(CMD_STAT, path)
File "/usr/lib/python2.6/site-packages/paramiko/sftp_client.py", line 624, in _request
return self._read_response(num)
File "/usr/lib/python2.6/site-packages/paramiko/sftp_client.py", line 671, in _read_response
self._convert_status(msg)
File "/usr/lib/python2.6/site-packages/paramiko/sftp_client.py", line 697, in _convert_status
raise IOError(errno.ENOENT, text)
IOError: [Errno 2] No such file
SFTPClient.listdir returns file names only, not a full path. So to use the filename in another API, you have to add a path:
for i in sftp.listdir(path):
info = sftp.stat(path + "/" + i)
print info.st_size
Though that's inefficient. Paramiko knows the size already, you are just throwing the information away by using SFTPClient.listdir instead of SFTPClient.listdir_attr (listdir calls listdir_attr internally).
for i in sftp.listdir_attr(path):
print i.st_size

how to switch user and pass password using paramiko

I am using a Python script which requires to have root access.
First I am becoming a normal user, then I want to become root. But, stdin.write is still throwing error.
Here is my script:
import os
import paramiko
import subprocess
user="a554511"
p="xxxxxxx"
root="abcdefgh"
x="vljhggsajgfj"
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(x,username=user,password=p)
stdin.write('su -')
stdin.write("\n")
stdin.write(root)
stdin.flush()
stdin,stdout,stderr=ssh.exec_command('pwd')
x=stdout.readlines()
print(x)
ssh.close()
The error I get is:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.6/site-packages/paramiko-1.15.2-py2.6.egg/paramiko/file.py", line 339, in write
self._write_all(data)
File "/usr/lib/python2.6/site-packages/paramiko-1.15.2-py2.6.egg/paramiko/file.py", line 456, in _write_all
count = self._write(data)
File "/usr/lib/python2.6/site-packages/paramiko-1.15.2-py2.6.egg/paramiko/channel.py", line 1220, in _write
self.channel.sendall(data)
File "/usr/lib/python2.6/site-packages/paramiko-1.15.2-py2.6.egg/paramiko/channel.py", line 744, in sendall
sent = self.send(s)
File "/usr/lib/python2.6/site-packages/paramiko-1.15.2-py2.6.egg/paramiko/channel.py", line 698, in send
return self._send(s, m)
File "/usr/lib/python2.6/site-packages/paramiko-1.15.2-py2.6.egg/paramiko/channel.py", line 1058, in _send
raise socket.error('Socket is closed')
socket.error: Socket is closed

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

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.

Categories