"SSHException('No existing session')" errors with python ncclient - paramiko

I am working on the code below, and I got SSHException('No existing session') error
from ncclient import manager
with manager.connect(host="192.168.1.40", port=830, username="cisco", password="cisco", hostkey_verify=False, device_params={'name':'iosxr'}, ssh_config=True, allow_agent=False,look_for_keys=False, timeout=10) as nc_conn:
nc_config = nc_conn.get_config(source='running').data_xml
print (nc_config)
yapi#MacBook-Pro-3 iTel % python test01.py
Traceback (most recent call last):
File "/Users/yapi/Documents/Scripts/Non-GIT/Python/2023/iTel/test01.py", line 4, in
with manager.connect(host="192.168.1.40", port=830, username="abdul", password="cisco", hostkey_verify=False, device_params={'name':'iosxr'}, ssh_config=True, allow_agent=False,look_for_keys=False, timeout=10) as nc_conn:
File "/usr/local/lib/python3.9/site-packages/ncclient/manager.py", line 176, in connect
return connect_ssh(*args, **kwds)
File "/usr/local/lib/python3.9/site-packages/ncclient/manager.py", line 143, in connect_ssh
session.connect(*args, **kwds)
File "/usr/local/lib/python3.9/site-packages/ncclient/transport/ssh.py", line 364, in connect
self._auth(username, password, key_filenames, allow_agent, look_for_keys)
File "/usr/local/lib/python3.9/site-packages/ncclient/transport/ssh.py", line 480, in _auth
raise AuthenticationError(repr(saved_exception))
ncclient.transport.errors.AuthenticationError: SSHException('No existing session')
yapi#MacBook-Pro-3 iTel %
I have tried using different flags in connect function, but no luck

Related

Setting up Chrome DevTools (Selenium 4) Using Remote WebDriver in Python

I've been trying to set up the use of the Chrome DevTools using Selenium 4 and Python. I've been able to get it to run locally (without any of the async stuff), but when I try to use the webdriver.Remote implementation, it crashes.
Here is an example from the Selenium docs: https://www.selenium.dev/de/documentation/support_packages/chrome_devtools/
Below is how I tried to run it.
import asyncio
from selenium import webdriver
import selenium.webdriver.common.devtools.v96 as devtools
async def geo_location_test():
try:
chrome_options = webdriver.ChromeOptions()
driver = webdriver.Remote(
command_executor='http://D5365900:4444/wd/hub',
options=chrome_options
)
async with driver.bidi_connection() as session:
cdp_session = session.session
await cdp_session.execute(devtools.emulation.set_geolocation_override(latitude=41.8781,
longitude=-87.6298,
accuracy=100))
driver.get("https://my-location.org/")
finally:
driver.quit()
async def main():
await geo_location_test()
if __name__ == "__main__":
asyncio.run(main())
It runs up to the line async with driver.bidi_connection() as session: (session is established and Chrome browser opens). But the it crashes with the following trace.
Traceback (most recent call last):
File "C:\Users\y04082\eclipse-workspace\WWI-Testautomation\TestScripts\Josh\async_sel_4.py", line 54, in <module>
asyncio.run(main())
File "C:\Program Files\Python310\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Program Files\Python310\lib\asyncio\base_events.py", line 641, in run_until_complete
return future.result()
File "C:\Users\y04082\eclipse-workspace\WWI-Testautomation\TestScripts\Josh\async_sel_4.py", line 51, in main
await geo_location_test()
File "C:\Users\y04082\eclipse-workspace\WWI-Testautomation\TestScripts\Josh\async_sel_4.py", line 40, in geo_location_test
async with driver.bidi_connection() as session:
File "C:\Program Files\Python310\lib\contextlib.py", line 199, in __aenter__
return await anext(self.gen)
File "C:\Program Files\Python310\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 1576, in bidi_connection
async with cdp.open_cdp(ws_url) as conn:
File "C:\Program Files\Python310\lib\contextlib.py", line 199, in __aenter__
return await anext(self.gen)
File "C:\Program Files\Python310\lib\site-packages\selenium\webdriver\common\bidi\cdp.py", line 457, in open_cdp
async with trio.open_nursery() as nursery:
File "C:\Program Files\Python310\lib\site-packages\trio\_core\_run.py", line 796, in __aenter__
self._scope.__enter__()
File "C:\Program Files\Python310\lib\site-packages\trio\_core\_ki.py", line 159, in wrapper
return fn(*args, **kwargs)
File "C:\Program Files\Python310\lib\site-packages\trio\_core\_run.py", line 449, in __enter__
task = _core.current_task()
File "C:\Program Files\Python310\lib\site-packages\trio\_core\_run.py", line 2285, in current_task
raise RuntimeError("must be called from async context") from None
RuntimeError: must be called from async context
As you can see, I'm using Python 3.10. I also upgraded the Selenium bindings to 4.1.0 and am running a Selenium 4.0.0 Hub/Node config to automate Chrome 96.
Any ideas, what is the problem here? Am I handling the asynchronous coroutines incorrectly?
Any help is much appreciated!
Update
After trying to run it with trio (as suggested in Henry Ashton-Martyn's comment), I get the following error.
Traceback (most recent call last):
File "C:\Program Files\Python310\lib\site-packages\trio\_highlevel_open_tcp_stream.py", line 332, in attempt_connect
await sock.connect(sockaddr)
File "C:\Program Files\Python310\lib\site-packages\trio\_socket.py", line 682, in connect
raise OSError(err, "Error in connect: " + os.strerror(err))
OSError: [Errno 10049] Error in connect: Unknown error
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\y04082\eclipse-workspace\WWI-Testautomation\TestScripts\Josh\async_sel_4.py", line 58, in <module>
trio.run(main)
File "C:\Program Files\Python310\lib\site-packages\trio\_core\_run.py", line 1932, in run
raise runner.main_task_outcome.error
File "C:\Users\y04082\eclipse-workspace\WWI-Testautomation\TestScripts\Josh\async_sel_4.py", line 55, in main
await geo_location_test()
File "C:\Users\y04082\eclipse-workspace\WWI-Testautomation\TestScripts\Josh\async_sel_4.py", line 44, in geo_location_test
async with driver.bidi_connection() as session:
File "C:\Program Files\Python310\lib\contextlib.py", line 199, in __aenter__
return await anext(self.gen)
File "C:\Program Files\Python310\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 1576, in bidi_connection
async with cdp.open_cdp(ws_url) as conn:
File "C:\Program Files\Python310\lib\contextlib.py", line 199, in __aenter__
return await anext(self.gen)
File "C:\Program Files\Python310\lib\site-packages\selenium\webdriver\common\bidi\cdp.py", line 458, in open_cdp
conn = await connect_cdp(nursery, url)
File "C:\Program Files\Python310\lib\site-packages\selenium\webdriver\common\bidi\cdp.py", line 479, in connect_cdp
ws = await connect_websocket_url(nursery, url,
File "C:\Program Files\Python310\lib\site-packages\trio_websocket\_impl.py", line 262, in connect_websocket_url
return await connect_websocket(nursery, host, port, resource,
File "C:\Program Files\Python310\lib\site-packages\trio_websocket\_impl.py", line 171, in connect_websocket
stream = await trio.open_tcp_stream(host, port)
File "C:\Program Files\Python310\lib\site-packages\trio\_highlevel_open_tcp_stream.py", line 367, in open_tcp_stream
raise OSError(msg) from trio.MultiError(oserrors)
OSError: all attempts to connect to 0.0.0.0:4444 failed
It seems that selenium doesn't use python's builtin async framework but uses a package called trio as well. You should be able to fix this problem by changing this code from:
if __name__ == "__main__":
asyncio.run(main())
to:
if __name__ == "__main__":
import trio
trio.run(main)

sqllite argumentError absolute path

I am trying to create a sqlite database using windows and I have an error "ArgumentError: Invalid SQLite URL: sqlite://search.db" What is the absolute path syntax for creating an SQL lite db.
'sqlite://C:/Users..../search.db'
>>> from flaskapp import db
C:\Users\champ\Python_proj\main_env\lib\site-packages\flask_sqlalchemy\__init__.py:833: FSADeprecationWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future. Set it to True or False to suppress this warning.
warnings.warn(FSADeprecationWarning(
>>> db.create_all()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\champ\Python_proj\main_env\lib\site-packages\flask_sqlalchemy\__init__.py", line 1039, in create_all
self._execute_for_all_tables(app, bind, 'create_all')
File "C:\Users\champ\Python_proj\main_env\lib\site-packages\flask_sqlalchemy\__init__.py", line 1031, in _execute_for_all_tables
op(bind=self.get_engine(app, bind), **extra)
File "C:\Users\champ\Python_proj\main_env\lib\site-packages\flask_sqlalchemy\__init__.py", line 962, in get_engine
return connector.get_engine()
File "C:\Users\champ\Python_proj\main_env\lib\site-packages\flask_sqlalchemy\__init__.py", line 556, in get_engine
self._engine = rv = self._sa.create_engine(sa_url, options)
File "C:\Users\champ\Python_proj\main_env\lib\site-packages\flask_sqlalchemy\__init__.py", line 972, in create_engine
return sqlalchemy.create_engine(sa_url, **engine_opts)
File "C:\Users\champ\Python_proj\main_env\lib\site-packages\sqlalchemy\engine\__init__.py", line 488, in create_engine
return strategy.create(*args, **kwargs)
File "C:\Users\champ\Python_proj\main_env\lib\site-packages\sqlalchemy\engine\strategies.py", line 98, in create
(cargs, cparams) = dialect.create_connect_args(u)
File "C:\Users\champ\Python_proj\main_env\lib\site-packages\sqlalchemy\dialects\sqlite\pysqlite.py", line 466, in create_connect_args
raise exc.ArgumentError(
sqlalchemy.exc.ArgumentError: Invalid SQLite URL: sqlite://search.db
Valid SQLite URL forms are:
sqlite:///:memory: (or, sqlite://)
sqlite:///relative/path/to/file.db
sqlite:////absolute/path/to/file.db

AuthorizationFailed - "The client 'xxx' with object id 'xxx does not have authorization to perform action

I've tried to get Workspace from config which I do have access to, but it fails with the following error:
import azureml.core
print("SDK version:", azureml.core.VERSION)
from azureml.core.workspace import Workspace
ws = Workspace.from_config()
print(ws.name, ws.resource_group, ws.location, ws.subscription_id, sep='\n')
SDK version: 0.1.80 Found the config file in:
C:\Users\gubert\Repos\Gimmonix\HotelMappingAI\aml_config\config.json
get_workspace error using subscription_id=xxxxxxxxxxxxxxxxxxxxxxx,
resource_group_name=xxxxxxxxxxxx, workspace_name=gmx-ml-mapping
Traceback (most recent call last): File
"C:\Users\gubert.azureml\envs\myenv\lib\site-packages\azureml_project_commands.py",
line 320, in get_workspace workspace_name) File
"C:\Users\gubert.azureml\envs\myenv\lib\site-packages\azureml_base_sdk_common\workspace\operations\workspaces_operations.py",
line 78, in get raise
models.ErrorResponseWrapperException(self._deserialize, response)
azureml._base_sdk_common.workspace.models.error_response_wrapper.ErrorResponseWrapperException:
Operation returned an invalid status code 'Forbidden'
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File
"c:\Users\gubert.vscode\extensions\ms-python.python-2018.10.1\pythonFiles\experimental\ptvsd_launcher.py",
line 38, in main(sys.argv) File
"c:\Users\gubert.vscode\extensions\ms-python.python-2018.10.1\pythonFiles\experimental\ptvsd\ptvsd_main_.py",
line 265, in main wait=args.wait) File
"c:\Users\gubert.vscode\extensions\ms-python.python-2018.10.1\pythonFiles\experimental\ptvsd\ptvsd_main_.py",
line 256, in handle_args run_main(addr, name, kind, *extra, **kwargs)
File
"c:\Users\gubert.vscode\extensions\ms-python.python-2018.10.1\pythonFiles\experimental\ptvsd\ptvsd_local.py",
line 52, in run_main runner(addr, name, kind == 'module', *extra,
**kwargs) File "c:\Users\gubert.vscode\extensions\ms-python.python-2018.10.1\pythonFiles\experimental\ptvsd\ptvsd\runner.py",
line 32, in run set_trace=False) File
"c:\Users\gubert.vscode\extensions\ms-python.python-2018.10.1\pythonFiles\experimental\ptvsd\ptvsd_vendored\pydevd\pydevd.py",
line 1283, in run return self._exec(is_module, entry_point_fn,
module_name, file, globals, locals) File
"c:\Users\gubert.vscode\extensions\ms-python.python-2018.10.1\pythonFiles\experimental\ptvsd\ptvsd_vendored\pydevd\pydevd.py",
line 1290, in _exec pydev_imports.execfile(file, globals, locals) #
execute the script File
"c:\Users\gubert.vscode\extensions\ms-python.python-2018.10.1\pythonFiles\experimental\ptvsd\ptvsd_vendored\pydevd_pydev_imps_pydev_execfile.py",
line 25, in execfile exec(compile(contents+"\n", file, 'exec'), glob,
loc) File "c:\Users\gubert\Repos\Gimmonix\HotelMappingAI\test.py",
line 8, in ws = Workspace.from_config() File
"C:\Users\gubert.azureml\envs\myenv\lib\site-packages\azureml\core\workspace.py",
line 153, in from_config auth=auth) File
"C:\Users\gubert.azureml\envs\myenv\lib\site-packages\azureml\core\workspace.py",
line 86, in init auto_rest_workspace = _commands.get_workspace(auth,
subscription_id, resource_group, workspace_name) File
"C:\Users\gubert.azureml\envs\myenv\lib\site-packages\azureml_project_commands.py",
line 326, in get_workspace resource_error_handling(response_exception,
WORKSPACE) File
"C:\Users\gubert.azureml\envs\myenv\lib\site-packages\azureml_base_sdk_common\common.py",
line 270, in resource_error_handling raise
ProjectSystemException(response_message)
azureml.exceptions._azureml_exception.ProjectSystemException: {
"error_details": { "error": { "code": "AuthorizationFailed",
"message": "The client 'xxxxxxxxxx#microsoft.com' with object id
'xxxxxxxxxxxxx' does not have authorization to perform action
'Microsoft.MachineLearningServices/workspaces/read' over scope
'/subscriptions/xxxxxxxxxxxxxx/resourceGroups/CarsolizeCloud - Test
Global/providers/Microsoft.MachineLearningServices/workspaces/gmx-ml-mapping'."
} }, "status_code": 403, "url":
"https://management.azure.com/subscriptions/xxxxxxxxxxxxx/resourceGroups/CarsolizeCloud%20-%20Test%20Global/providers/Microsoft.MachineLearningServices/workspaces/gmx-ml-mapping?api-version=2018-03-01-preview"
}
Try using the newest SDK version 1.0.10, this is a fairly old preview version you're using. If you still have a problem, let me know as I work on this SDK.

How to add an edge to existing and new vertices in gremlin-python?

I've already seen this answer:
Gremlin, How to add edge to existing vertex in gremlin-python
and it wasn't really helpful. As suggested in one of the comments I did try to update gremlinpython 3.3.0 but then I get key error.
Stack:
JanusGraph 0.2.0, gremlinpython3.2.3
This is my code
from gremlin_python import statics
from gremlin_python.structure.graph import Graph
from gremlin_python.process.graph_traversal import __
from gremlin_python.process.strategies import *
from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection
graph = Graph()
g = graph.traversal().withRemote(DriverRemoteConnection('ws://localhost:8182/gremlin','g'))
martha = g.V().has('name','martha').next()
jack = g.V().has('name','jack').next()
#e_id = g.addE(jack,'likes',martha).next()
e_id = g.V(martha).as_('to').V(jack).addE("Likes").to('to').toList()
print e_id.toList()
StackTrace with gremlinpython 3.3.0
Traceback (most recent call last):
File "gremlin-py.py", line 9, in <module>
martha = g.V().has('name','martha').next()
File "/Users/arvindn/.virtualenvs/gremlinenv/lib/python2.7/site-packages/gremlin_python/process/traversal.py", line 70,in next
return self.__next__()
File "/Users/arvindn/.virtualenvs/gremlinenv/lib/python2.7/site-packages/gremlin_python/process/traversal.py", line 43,in __next__
self.traversal_strategies.apply_strategies(self)
File "/Users/arvindn/.virtualenvs/gremlinenv/lib/python2.7/site-packages/gremlin_python/process/traversal.py", line 352, in apply_strategies
traversal_strategy.apply(traversal)
File "/Users/arvindn/.virtualenvs/gremlinenv/lib/python2.7/site-packages/gremlin_python/driver/remote_connection.py", line 143, in apply
remote_traversal = self.remote_connection.submit(traversal.bytecode)
File "/Users/arvindn/.virtualenvs/gremlinenv/lib/python2.7/site-packages/gremlin_python/driver/driver_remote_connection.py", line 54, in submit
results = result_set.all().result()
File "/Users/arvindn/.virtualenvs/gremlinenv/lib/python2.7/site-packages/concurrent/futures/_base.py", line 429, in result
return self.__get_result()
File "/Users/arvindn/.virtualenvs/gremlinenv/lib/python2.7/site-packages/concurrent/futures/_base.py", line 381, in __get_result
raise exception_type, self._exception, self._traceback
KeyError: None
In my case, 3.3.0 is throwing error for all queries including g.V().next(). Now going back to 3.2.3, addvertex and other queries are working absolutely fine, but I couldn't figure out how to add edges. The same code when run with 3.2.3 produces,
StackTrace with gremlinpython 3.2.3
Traceback (most recent call last): File "gremlin-py.py", line 12, in <module>
e_id = g.V(martha).as_('to').V(jack).addE("Likes").to('to').toList()
File "/Users/arvindn/.virtualenvs/gremlinenv/lib/python2.7/site-packages/gremlin_python/process/traversal.py", line 52, in toList return list(iter(self))
File "/Users/arvindn/.virtualenvs/gremlinenv/lib/python2.7/site-packages/gremlin_python/process/traversal.py", line 70, in next
return self.__next__() File "/Users/arvindn/.virtualenvs/gremlinenv/lib/python2.7/site-packages/gremlin_python/process/traversal.py", line 43, in __next__
self.traversal_strategies.apply_strategies(self) File "/Users/arvindn/.virtualenvs/gremlinenv/lib/python2.7/site-packages/gremlin_python/process/traversal.py", line 284, in apply_strategies
traversal_strategy.apply(traversal)
File "/Users/arvindn/.virtualenvs/gremlinenv/lib/python2.7/site-packages/gremlin_python/driver/remote_connection.py", line 95, in apply remote_traversal = self.remote_connection.submit(traversal.bytecode) File "/Users/arvindn/.virtualenvs/gremlinenv/lib/python2.7/site-packages/gremlin_python/driver/driver_remote_connection.py", line 53, in submit traversers = self._loop.run_sync(lambda: self.submit_traversal_bytecode(request_id, bytecode))
File "/Users/arvindn/.virtualenvs/gremlinenv/lib/python2.7/site-packages/tornado/ioloop.py", line 457, in run_sync
return future_cell[0].result() File "/Users/arvindn/.virtualenvs/gremlinenv/lib/python2.7/site-packages/tornado/concurrent.py", line 237, in result
raise_exc_info(self._exc_info)
File "/Users/arvindn/.virtualenvs/gremlinenv/lib/python2.7/site-packages/tornado/gen.py", line 285, in wrapper
yielded = next(result)
File "/Users/arvindn/.virtualenvs/gremlinenv/lib/python2.7/site-packages/gremlin_python/driver/driver_remote_connection.py", line 69, in submit_traversal_bytecode
"gremlin": self._graphson_writer.writeObject(bytecode),
File "/Users/arvindn/.virtualenvs/gremlinenv/lib/python2.7/site-packages/gremlin_python/structure/io/graphson.py", line 72, in writeObject
return json.dumps(self.toDict(objectData), separators=(',', ':'))
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 250, in dumps
sort_keys=sort_keys, **kw).encode(obj)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 207, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 270, in iterencode
return _iterencode(o, 0)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 184, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: v[4184] is not JSON serializable
It says v[x] is not JSON serializable. I'm not sure what causes this error. It'll be awesome if someone can help. If any more info is needed, I shall update the question accordingly.
JanusGraph 0.2.0 uses Apache TinkerPop 3.2.6. You should use the 3.2.6 version of the gremlinpython driver.
pip uninstall gremlinpython
pip install gremlinpython==3.2.6

"Adapter does not support geometry" exception when declaring geometry field

In my application, an "Adapter does not support geometry" exception is being thrown when attempting to create a field of type, "geometry()". For my test application, I'm using an sqlite DB (production will use postgres):
db = DAL('sqlite://storage.sqlite', pool_size = 1, fake_migrate_all= False)
The DB table in question is declared within a class, inside of a module, and contains a several fields, some of which contain location data:
from gluon.dal import Field, geoPoint, geoLine, geoPolygon
class Info(Base_Model):
def __init__(...):
try:
db.define_table('t_info',
...
Field('f_geolocation', type='geometry()',
label = current.T('Geolocation')),
Field('f_city', type='string',
label = current.T('City')),
...
except Exception as e:
...
Edit:
As per Anthony's suggestion, I've modified the DAL constructor call to the following:
db = DAL('spatialite://storage.sqlite', pool_size = 1)
It produces the following error message:
Traceback (most recent call last):
File "C:\...\web2py\gluon\restricted.py", line 227, in restricted
exec ccode in environment
File "C:/My_Stuff/Programs/web2py/applications/Proj/models/db.py", line 38, in <module>
db = DAL('spatialite://storage.sqlite', pool_size = 1)
File "C:\...\web2py\gluon\packages\dal\pydal\base.py", line 171, in __call__
obj = super(MetaDAL, cls).__call__(*args, **kwargs)
File "C:\...\web2py\gluon\packages\dal\pydal\base.py", line 457, in __init__
raise RuntimeError("Failure to connect, tried %d times:\n%s" % (attempts, tb))
RuntimeError: Failure to connect, tried 5 times:
Traceback (most recent call last):
File "C:\...\web2py\gluon\packages\dal\pydal\base.py", line 435, in __init__
self._adapter = ADAPTERS[self._dbname](**kwargs)
File "C:\...\web2py\gluon\packages\dal\pydal\adapters\base.py", line 53, in __call__
obj = super(AdapterMeta, cls).__call__(*args, **kwargs)
File "C:\...\web2py\gluon\packages\dal\pydal\adapters\sqlite.py", line 169, in __init__
if do_connect: self.reconnect()
File "C:\...\web2py\gluon\packages\dal\pydal\connection.py", line 129, in reconnect
self.after_connection_hook()
File "C:\...\web2py\gluon\packages\dal\pydal\connection.py", line 81, in after_connection_hook
self.after_connection()
File "C:\...\web2py\gluon\packages\dal\pydal\adapters\sqlite.py", line 177, in after_connection
self.execute(r'SELECT load_extension("%s");' % libspatialite)
File "C:\...\web2py\gluon\packages\dal\pydal\adapters\base.py", line 1326, in execute
return self.log_execute(*a, **b)
File "C:\...\web2py\gluon\packages\dal\pydal\adapters\base.py", line 1320, in log_execute
ret = self.cursor.execute(command, *a[1:], **b)
OperationalError: The specified module could not be found.
If you want to use geometry fields with SQLite, you must use the spatialite adapter, which makes use of the SpatialLite extension for SQLite:
db = DAL('spatialite://storage.sqlite', pool_size = 1)
Note, you must have spatialite installed for this to work.

Resources