netmiko key authentication failure - netmiko

Seeing some issue with netmiko KEY authentication with N7K.
Python 3.8.10, netmiko 4.1.2.
Firstly tried on N9K without any issue, command can be sent after get the connection.
Python 3.8.10 (default, Jun 22 2022, 20:18:18)
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from netmiko import ConnectHandler
>>> n9k = {"device_type": "cisco_nxos", "host": "10.1.1.10", "username": "admin", "use_keys": True,"key_file":"~/.ssh/id_rsa", "passphrase": "Cisco123"}
>>> target_con = ConnectHandler(**n9k)
Hit the issue when trying the connection to a N7K switch.
>>> n7k = {"device_type": "cisco_nxos", "host": "10.1.1.20", "username": "admin", "use_keys": True,"key_file":"~/.ssh/id_rsa", "passphrase": "Cisco123"}
>>> target_con = ConnectHandler(**n7k)
Traceback (most recent call last):
File "/home/admin/netmiko_test/lib/python3.8/site-packages/netmiko/base_connection.py", line 1046, in establish_connection
self.remote_conn_pre.connect(**ssh_connect_params)
File "/home/admin/netmiko_test/lib/python3.8/site-packages/paramiko/client.py", line 435, in connect
self._auth(
File "/home/admin/netmiko_test/lib/python3.8/site-packages/paramiko/client.py", line 771, in _auth
raise saved_exception
File "/home/admin/netmiko_test/lib/python3.8/site-packages/paramiko/client.py", line 747, in _auth
self._transport.auth_publickey(username, key)
File "/home/admin/netmiko_test/lib/python3.8/site-packages/paramiko/transport.py", line 1635, in auth_publickey
return self.auth_handler.wait_for_response(my_event)
File "/home/admin/netmiko_test/lib/python3.8/site-packages/paramiko/auth_handler.py", line 259, in wait_for_response
raise e
paramiko.ssh_exception.AuthenticationException: Authentication failed.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/admin/netmiko_test/lib/python3.8/site-packages/netmiko/ssh_dispatcher.py", line 365, in ConnectHandler
return ConnectionClass(*args, **kwargs)
File "/home/admin/netmiko_test/lib/python3.8/site-packages/netmiko/base_connection.py", line 439, in __init__
self._open()
File "/home/admin/netmiko_test/lib/python3.8/site-packages/netmiko/base_connection.py", line 444, in _open
self.establish_connection()
File "/home/admin/netmiko_test/lib/python3.8/site-packages/netmiko/base_connection.py", line 1083, in establish_connection
raise NetmikoAuthenticationException(msg)
netmiko.exceptions.NetmikoAuthenticationException: Authentication to device failed.
Common causes of this problem are:
1. Invalid username and password
2. Incorrect SSH-key file
3. Connecting to the wrong device
Device settings: cisco_nxos 10.1.1.20:22
Authentication failed.
>>>
The username and ssh key have been validated. All work well if using username/password instead.
Any advice would be appreciated.
Thanks!

Found the issue when studying another similar paramiko problem.
The N9K node I tested against with uses openssh 8.3, thus it is rsa-sha2-256.
The N7K node uses openssh5.9 which is ssh-sha1.
That makes a difference as netmiko seems don't like ssh-sha1 by default.
Adding disabled_algorithms = {'pubkeys': ['rsa-sha2-256', 'rsa-sha2-512']} to ConnectHandler fixed the issue.

Related

unable to create executable using Py2exe, throwing error as mentioned below

Hi I'm trying to make an executable using py2exe, I checked my script but cannot find the actual issue why below error is keep getting pop-up during building of exe
Building 'dist\py.exe'.
Traceback (most recent call last):
File "C:\Users\User\PycharmProjects\Test\pyexe\setup.py", line 15, in <module>
freeze(
File "C:\Python39\lib\site-packages\py2exe\__init__.py", line 176, in freeze
builder.build()
File "C:\Python39\lib\site-packages\py2exe\runtime.py", line 254, in build
self.build_archive(exe_path)
File "C:\Python39\lib\site-packages\py2exe\runtime.py", line 479, in build_archive
base = dist_path.rsplit('\\', 1)[0]
AttributeError: 'NoneType' object has no attribute 'rsplit'
Below is my setup.py script
from py2exe import freeze
from py_version import VERSION, DESCRIPTION # This is my own script
freeze(
console=[{"script": "py.py"}],
options={
"py2exe": {
"dist_dir": "dist",
"bundle_files": 1, # bundle as much as possible
"compressed": True,
}},
version_info={"version":VERSION,
"description":DESCRIPTION,
"company_name":"Priyanshu Kumar",
"copyright":"Opensource, credit goes to David Manthey",
"product_name":"Stand-Alone Python3 Interpreter",
"product_version":VERSION},
zipfile=None)
UPDATE:
I was searching on google for help and found that it should be <<<zipfile="None">>> instead of <<<zipfile=None>>>.
I changed it in my code but now got new error
Traceback (most recent call last):
File "C:\Users\User\PycharmProjects\Test\pyexe\setup.py", line 29, in <module>
options={
File "C:\Python39\lib\site-packages\py2exe\__init__.py", line 176, in freeze
builder.build()
File "C:\Python39\lib\site-packages\py2exe\runtime.py", line 273, in build
self.build_archive(libpath, delete_existing_resources=True)
File "C:\Python39\lib\site-packages\py2exe\runtime.py", line 397, in build_archive
resource.add(type=os.path.basename(pydll), name=1, value=pydll_bytes)
File "C:\Python39\lib\site-packages\py2exe\resources.py", line 49, in add
raise WindowsError(details) from None
OSError: [WinError 87] The parameter is incorrect.
Press any key to continue . . .

bot.get_me() doesn't work and raises an error

I can manually interact with the bot through url. For example when I send a request to api.telegram.com/bot-token/getMe
the bot's basic info is returned I even get correct results using requests library in python shell but when I try bot.get_me() in the python shell it doesn't work and says this
Traceback (most recent call last):
File "C:\Users\YM\AppData\Local\Programs\Python\Python38-32\lib\site-packages\
telegram\vendor\ptb_urllib3\urllib3\connection.py", line 140, in _new_conn
conn = connection.create_connection(
File "C:\Users\YM\AppData\Local\Programs\Python\Python38-32\lib\site-packages\
telegram\vendor\ptb_urllib3\urllib3\util\connection.py", line 83, in create_conn
ection
raise err
File "C:\Users\YM\AppData\Local\Programs\Python\Python38-32\lib\site-packages\
telegram\vendor\ptb_urllib3\urllib3\util\connection.py", line 73, in create_conn
ection
sock.connect(sa)
socket.timeout: timed out
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\YM\AppData\Local\Programs\Python\Python38-32\lib\site-packages\
telegram\vendor\ptb_urllib3\urllib3\connectionpool.py", line 614, in urlopen
httplib_response = self._make_request(conn, method, url,
File "C:\Users\YM\AppData\Local\Programs\Python\Python38-32\lib\site-packages\
telegram\vendor\ptb_urllib3\urllib3\connectionpool.py", line 360, in _make_reque
st
self._validate_conn(conn)
File "C:\Users\YM\AppData\Local\Programs\Python\Python38-32\lib\site-packages\
telegram\vendor\ptb_urllib3\urllib3\connectionpool.py", line 857, in _validate_c
onn
super(HTTPSConnectionPool, self)._validate_conn(conn)
File "C:\Users\YM\AppData\Local\Programs\Python\Python38-32\lib\site-packages\
telegram\vendor\ptb_urllib3\urllib3\connectionpool.py", line 289, in _validate_c
onn
conn.connect()
File "C:\Users\YM\AppData\Local\Programs\Python\Python38-32\lib\site-packages\
telegram\vendor\ptb_urllib3\urllib3\connection.py", line 284, in connect
conn = self._new_conn()
File "C:\Users\YM\AppData\Local\Programs\Python\Python38-32\lib\site-packages\
telegram\vendor\ptb_urllib3\urllib3\connection.py", line 144, in _new_conn
raise ConnectTimeoutError(
telegram.vendor.ptb_urllib3.urllib3.exceptions.ConnectTimeoutError: (<telegram.v
endor.ptb_urllib3.urllib3.connection.VerifiedHTTPSConnection object at 0x024257F
0>, 'Connection to api.telegram.org timed out. (connect timeout=5.0)')
Looks like you're having problems with your internet connection, i.e. the request could not be finished within the timeout of 5 seconds. Keep in mind that a lot of problems can happen unexpectedly in networking. In fact python-telegram-bot has a wiki page dedicated to that topic. Ofc you could first try to simply increase the timeout, e.g. by passing timeout=<some_value_>5> to get_me.

azure-sdk-python status code not found GraphRbacManagementClient

I am trying to enumerate Azure AD users from an azure subscription, with this code:
WORKING_DIRECTORY = os.getcwd()
TENANT_ID = "REDACTED_AZURE_ID_OF_MY_AZURE_AD_USER"
AZURE_AUTH_LOCATION = os.path.join(WORKING_DIRECTORY, "mycredentials.json") # from: az ad sp create-for-rbac --sdk-auth > mycredentials.json
# I've tried with get_client_from_cli_profile() while logged in azure CLI
# I've tried with and without parameters auth_path and tenant_id
rbac_client = get_client_from_auth_file(GraphRbacManagementClient,auth_path=AZURE_AUTH_LOCATION, tenant_id=TENANT_ID)
# Try to list users
for user in rbac_client.users.list():
pprint(user.__dict__)
As I've detailed in the comments, I've tried to fix the issue with a couple of unsuccessful attempts, here is the stacktrace
/home/guillaumedsde/.virtualenvs/champollion/bin/python /home/guillaumedsde/PycharmProjects/champollion/champollion/champollion.py
Traceback (most recent call last):
File "/home/guillaumedsde/PycharmProjects/champollion/champollion/champollion.py", line 582, in <module>
gitlab_project_member.access_level)
File "/home/guillaumedsde/PycharmProjects/champollion/champollion/champollion.py", line 306, in create_role_assignment
"principal_id": get_user_azure_id(user)} # get_user_azure_id(user)} # TODO
File "/home/guillaumedsde/PycharmProjects/champollion/champollion/champollion.py", line 329, in get_user_azure_id
for user in rbac_client.users.list():
File "/home/guillaumedsde/.virtualenvs/champollion/lib/python3.6/site-packages/msrest/paging.py", line 131, in __next__
self.advance_page()
File "/home/guillaumedsde/.virtualenvs/champollion/lib/python3.6/site-packages/msrest/paging.py", line 117, in advance_page
self._response = self._get_next(self.next_link)
File "/home/guillaumedsde/.virtualenvs/champollion/lib/python3.6/site-packages/azure/graphrbac/operations/users_operations.py", line 158, in internal_paging
raise models.GraphErrorException(self._deserialize, response)
azure.graphrbac.models.graph_error.GraphErrorException: Operation returned an invalid status code 'Not Found'
Process finished with exit code 1
Was a bug fixed in azure-common 1.1.13
https://pypi.org/project/azure-common/1.1.13/
You can now simply do that (with no tenant ID)
rbac_client = get_client_from_auth_file(GraphRbacManagementClient,auth_path=AZURE_AUTH_LOCATION)
I took this opportunity to fix the CLI version of this method as well.
(I own this code at MS)

paho-mqtt authentication error on pythonanywher

I am trying to publish to an mqtt topic on beebotte.com using a simple publish.single on my linux machine it works fine but on python anywhere I get an authentication error. There are small differences in minor version numbers, can that be what is different?
This is the code I put into the python console:
import paho.mqtt.publish as publish
mqtt_host = "beebotte.com"
mqtt_topic = "climate/set/livingroom"
auth = {'username':"token:MY_SECRET_TOKEN"}
publish.single(mqtt_topic, "python sent", hostname=mqtt_host, auth = auth)
this is the error:
Python 2.7.6 (default, Oct 26 2016, 20:30:19)
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import paho.mqtt.publish as publish
>>> mqtt_host = "beebotte.com"
>>> mqtt_topic = "climate/set/livingroom"
>>> auth = {'username':"MY_SECRET_TOKEN"}
>>> publish.single(mqtt_topic, "python sent", hostname=mqtt_host, auth = auth)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/<MYUSER>/python-email/local/lib/python2.7/site-packages/paho/mqtt/publish.py", line 216, in single
protocol, transport)
File "/home/<MYUSER>/python-email/local/lib/python2.7/site-packages/paho/mqtt/publish.py", line 152, in multiple
client.connect(hostname, port, keepalive)
File "/home/<MYUSER>/python-email/local/lib/python2.7/site-packages/paho/mqtt/client.py", line 768, in connect
return self.reconnect()
File "/home/<MYUSER>/python-email/local/lib/python2.7/site-packages/paho/mqtt/client.py", line 895, in reconnect
sock = socket.create_connection((self._host, self._port), source_address=(self._bind_address, 0))
File "/usr/lib/python2.7/socket.py", line 571, in create_connection
raise err
socket.error: [Errno 111] Connection refused
>>>
>>> exit()
and here it is working:
Python 2.7.13 (default, Nov 24 2017, 17:33:09)
[GCC 6.3.0 20170516] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import paho.mqtt.publish as publish
>>> mqtt_host = "beebotte.com"
>>> mqtt_topic = "climate/set/livingroom"
>>> auth = {'username':"MY_SECRET_TOKEN"}
>>> publish.single(mqtt_topic, "python sent", hostname=mqtt_host, auth = auth)
>>>
>>> exit()
edit (I'm not sure if this is true):
The key is in the actual format of token:token_KxDxlcmXgQBDfWRNC (not real) beebotte.com also accepts a so-called secret key in the format of 2A4Gfgv0puYFBEVbBQX24szALcyDvMRh If I use the secret key it works from pythonanywhere (sometimes). This is leading me to beleive it is some kind of formatting problem with the : in the token.
So the question now is how to format it to work properly.
I don't think mqtt will work from a free account on PythonAnywhere. Free accounts can only connect out through a proxy using http(s) to a specific whitelist of sites. If there's an http to mqtt bridge somewhere, you could possibly use that.

geocoder Service error in python

I am having a service error as I am trying to run geocoders from geopy to get a location coordinates in python.I have set my proxy config, given it an api_key.
Im not sure why I am getting this error. From the search that I have done on this, it seems that this might be a proxy issue but I have that set up already.
What could be the problem here?
This is my code :
from geopy import geocoders
proxies={'http': 'http://location:port', 'https': 'http://localhost:port'}
api_key = '.......'
g = geocoders.GoogleV3(api_key=api_key,proxies=proxies, timeout=10)
location = 'Mountain View, CA'
try:
place, (lat, lng) = g.geocode(location)
except ValueError as error_message:
print("Error: geocode failed on input %s with message %s" % (location, error_message))
this is my error output:
Traceback (most recent call last):
File "/Users/aqm1152/anaconda/lib/python3.5/urllib/request.py", line 1254, in do_open
h.request(req.get_method(), req.selector, req.data, headers)
File "/Users/aqm1152/anaconda/lib/python3.5/http/client.py", line 1106, in request
self._send_request(method, url, body, headers)
File "/Users/aqm1152/anaconda/lib/python3.5/http/client.py", line 1151, in _send_request
self.endheaders(body)
File "/Users/aqm1152/anaconda/lib/python3.5/http/client.py", line 1102, in endheaders
self._send_output(message_body)
File "/Users/aqm1152/anaconda/lib/python3.5/http/client.py", line 934, in _send_output
self.send(msg)
File "/Users/aqm1152/anaconda/lib/python3.5/http/client.py", line 877, in send
self.connect()
File "/Users/aqm1152/anaconda/lib/python3.5/http/client.py", line 1260, in connect
server_hostname=server_hostname)
File "/Users/aqm1152/anaconda/lib/python3.5/ssl.py", line 377, in wrap_socket
_context=self)
File "/Users/aqm1152/anaconda/lib/python3.5/ssl.py", line 752, in __init__
self.do_handshake()
File "/Users/aqm1152/anaconda/lib/python3.5/ssl.py", line 988, in do_handshake
self._sslobj.do_handshake()
File "/Users/aqm1152/anaconda/lib/python3.5/ssl.py", line 633, in do_handshake
self._sslobj.do_handshake()
ssl.SSLEOFError: EOF occurred in violation of protocol (_ssl.c:645)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/aqm1152/anaconda/lib/python3.5/site-packages/geopy/geocoders/base.py", line 143, in _call_geocoder
page = requester(req, timeout=(timeout or self.timeout), **kwargs)
File "/Users/aqm1152/anaconda/lib/python3.5/urllib/request.py", line 163, in urlopen
return opener.open(url, data, timeout)
File "/Users/aqm1152/anaconda/lib/python3.5/urllib/request.py", line 466, in open
response = self._open(req, data)
File "/Users/aqm1152/anaconda/lib/python3.5/urllib/request.py", line 484, in _open
'_open', req)
File "/Users/aqm1152/anaconda/lib/python3.5/urllib/request.py", line 444, in _call_chain
result = func(*args)
File "/Users/aqm1152/anaconda/lib/python3.5/urllib/request.py", line 1297, in https_open
context=self._context, check_hostname=self._check_hostname)
File "/Users/aqm1152/anaconda/lib/python3.5/urllib/request.py", line 1256, in do_open
raise URLError(err)
urllib.error.URLError: <urlopen error EOF occurred in violation of protocol (_ssl.c:645)>
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/aqm1152/Documents/TestingCode/ACERT/test_1.py", line 12, in <module>
place, (lat, lng) = g.geocode(location)
File "/Users/aqm1152/anaconda/lib/python3.5/site-packages/geopy/geocoders/googlev3.py", line 217, in geocode
self._call_geocoder(url, timeout=timeout), exactly_one
File "/Users/aqm1152/anaconda/lib/python3.5/site-packages/geopy/geocoders/base.py", line 171, in _call_geocoder
raise GeocoderServiceError(message)
geopy.exc.GeocoderServiceError: EOF occurred in violation of protocol (_ssl.c:645)
I modified your code as below, as I don't use proxy and apply an API, and it works in my machine.
from geopy import geocoders
#proxies={'http': 'http://location:port', 'https': 'http://localhost:port'}
#api_key = '.......'
g = geocoders.GoogleV3()
location = 'Mountain View, CA'
try:
place, (lat, lng) = g.geocode(location)
except ValueError as error_message:
print("Error: geocode failed on input %s with message %s" % (location, error_message))
print (place, lat, lng)
Here is the result.
Mountain View, CA, USA 37.3860517 -122.0838511
From the trackback, it looks all the errors are related to SSL. You may try to add below code at the beginning to disable SSL Certification verification as an alternative.
import ssl
# Disable SSL certificate verification
try:
_create_unverified_https_context = ssl._create_unverified_context
except AttributeError:
# Legacy Python that doesn't verify HTTPS certificates by default
pass
else:
# Handle target environment that doesn't support HTTPS verification
ssl._create_default_https_context = _create_unverified_https_context
I have encountered similar problem in Anaconda running Python 2.7 in a env with the root running Python 3.6. The problem wasn't encountered in Anaconda with both root and env running Python 2.7 in another machine.
In addition, this SO post about proxy server set up for geopy using os module may be good reference.
Hope this help.

Resources