Can not connect via AsyncSSH, error Host key is not trusted - python

When I run this script I receive SSH connection failed: Host key is not trusted error, but even connect to this host to take the key, keep to receive this error.
import asyncio, asyncssh, sys
async def run_client():
async with asyncssh.connect('172.18.17.9', username="user", password="admin", port=9321) as conn:
result = await conn.run('display version', check=True)
print(result.stdout, end='')
try:
asyncio.get_event_loop().run_until_complete(run_client())
except (OSError, asyncssh.Error) as exc:
sys.exit('SSH connection failed: ' + str(exc))

Try adding the known_hosts=None parameter to the connect method.
asyncssh.connect('172.18.17.9', username="user", password="admin", port=9321, known_hosts=None)
From asyncssh documentation here:
https://asyncssh.readthedocs.io/en/latest/api.html#asyncssh.SSHClientConnectionOptions
known_hosts (see Specifying known hosts) – (optional) The list of keys
which will be used to validate the server host key presented during
the SSH handshake. If this is not specified, the keys will be looked
up in the file .ssh/known_hosts. If this is explicitly set to None,
server host key validation will be disabled.

With me, it runs smoothly after inserting known_hosts=None
Here's my example when trying the coding sample in Ortega book:
I tried with hostname=ip/username/password of localCentOS, command test is ifconfig
import asyncssh
import asyncio
import getpass
async def execute_command(hostname, command, username, password):
async with asyncssh.connect(hostname, username = username,password=password,known_hosts=None) as connection:
result = await connection.run(command)
return result.stdout

You should always validate the server's public key.
Depending on your use case you can:
Get the servers host keys, bundle them with your app and explicitly pass them to asyncssh (e.g., as string with a path to your known_hosts file).
Manually connect to the server on the command line. SSH will then ask you if you want to trust the server. The keys are then added to ~/.ssh/known_hosts and AsyncSSH will use them.

This is related but maybe not totally your salvation:
https://github.com/ronf/asyncssh/issues/132
The real question you should be asking yourself as you ask this question (help us help you) is where is it all failing? Known-hosts via analogy is like env vars that don't show up when you need them to.
EDIT: Questions that immediately fire. Host key is found but not trusted? Hmm?
EDIT2: Not trying to be harsh towards you but I think it's a helpful corrective. You've got a software library that can find the key but is not known. You're going to come across a lot of scenarios with SSH / shell / env var stuff where things you take for granted aren't known. Think clearly to help yourself and to ask the question better.

Related

Access Azure EventHub with WebSocket and proxy

I'm trying to access Azure EvenHub but my network makes me use proxy and allows connection only over https (port 443)
Based on https://learn.microsoft.com/en-us/python/api/azure-eventhub/azure.eventhub.aio.eventhubproducerclient?view=azure-python
I added proxy configuration and TransportType.AmqpOverWebsocket parametr and my Producer looks like this:
async def run():
producer = EventHubProducerClient.from_connection_string(
"Endpoint=sb://my_eh.servicebus.windows.net/;SharedAccessKeyName=eh-sender;SharedAccessKey=MFGf5MX6Mdummykey=",
eventhub_name="my_eh",
auth_timeout=180,
http_proxy=HTTP_PROXY,
transport_type=TransportType.AmqpOverWebsocket,
)
and I get an error:
File "/usr/local/lib64/python3.9/site-packages/uamqp/authentication/cbs_auth_async.py", line 74, in create_authenticator_async
raise errors.AMQPConnectionError(
uamqp.errors.AMQPConnectionError: Unable to open authentication session on connection b'EHProducer-a1cc5f12-96a1-4c29-ae54-70aafacd3097'.
Please confirm target hostname exists: b'my_eh.servicebus.windows.net'
I don't know what might be the issue.
Might it be related to this one ? https://github.com/Azure/azure-event-hubs-c/issues/50#issuecomment-501437753
you should be able to set up a proxy that the SDK uses to access EventHub. Here is a sample that shows you how to set the HTTP_PROXY dictionary with the proxy information. Behind the scenes when proxy is passed in, it automatically goes over websockets.
As #BrunoLucasAzure suggested checking the ports on the proxy itself will be good to check, because based on the error message it looks like it made it past the proxy and cant resolve the endpoint.

Python - OPCDA read from remote server with OpenOPC

I have huge problem with OPCDA and OpenOPC. I should (must) read a set of tags from a remote server, I have no access to the machine in any way. I only know the IP and the OPC server name.
Testing OpenOPC locally with this code all work fine. Otherwise, changing the hostname with the remote one nothing work with 0x800706BA error.
import OpenOPC
import time
try:
opc = OpenOPC.client()
opc.servers()
#change localhost to remote
opc.connect('Matrikon.OPC.Simulation.1', 'localhost')
srvList = opc.list()
print(srvList)
tags = opc.read(opc.list('Simulation Items.Random.Int*'), group='myTest')
for name, value, quality, tagTime in opc.read(opc.list('Simulation Items.Random.Int*'), group='myTest'):
print(name, value, quality, tagTime)
for tag in tags:
print(tag)
except Exception as e:
print('OPC failed')
print(str(e))
pass
finally:
print('END')
Anyone have any ideas on this?
Not having access to the server (set with anonymous logon), I have done DCOM configurations as much as possible.
Does anyone know a procedure for a possible solution?
Thanks!

ServerSelectionTimeoutError errno 11001 getaddrinfo failed python

mongodb_uri = "mongodb://[username:password#]XX.XX.XX.XX"
client = MongoClient(mongodb_uri)
db = client['database']
print(db)
collection_taxonomy = db['collection']
doc = collection_taxonomy.find()
pprint.pprint(doc)
for each_doc in doc:
pprint.pprint(each_doc)
I am getting time out error as I try to print each document of the collection. However, I do not get time out error when I try to connect to localhost.
Tried connecting with connect=False
client = MongoClient(mongodb_uri,connect=False)
Still I get time out error while i print each document.
What could be wrong? Appreciate if someone can help me .
I am using Python 3.5 and Pymongo 3.5.1
Thanks,
-Roopa
is "mongodb://[username:password#]XX.XX.XX.XX" the actual value of mongodb_uri or have you substituted that for the value in your actual application?
The "getaddrinfo failed" message indicates that the hostname you put in mongodb_uri is invalid.
Removed square brackets([]) after substituting values in actual application.
"mongodb://username:password#XX.XX.XX.XX"
Works like a charm.!
Thanks a ton.
Roopa
I got the same error when i had a restricted rights on the user account which was trying to connect, so please try changing the user access rights or use a different account with higher privileges
user with the below rights failed
readWrite#dbname.colname
user with the below rights worked (note this is the user created for Atlas application)
atlasAdmin#admin
The URI should be like "mongodb://username:password#host", where the host is the hostname or IP.
This happened to me when I was connecting with the name, but the host name changed, so I changed the URI to connect via the machine's IP.

How to establish a SSH connection via proxy using Fabric?

I am trying to establish a SSH connection between a Windows PC and a Linux server(amazon ec2).
I decided to use Fabric API implemented using python.
I have Putty installed on the Windows PC.
My fabfile script looks like this:
import sys
from fabric.api import *
def testlive():
print 'Test live ...'
run("uptime")
env.use_ssh_config = False
env.host_string = "host.something.com"
env.user = "myuser"
env.keys_filename = "./private_openssh.key"
env.port = 22
env.gateway = "proxyhost:port"
testlive()
I am running Fabric in the same directory with the private key.
I am able to login on this machine using Putty.
The problem: I am constantly asked for Login password for specified user.
Based on other posts(here and here) I already tried:
pass as a list the key file to env.keys_filename
use username#host_string
use env.host instead of env.host_string
How to properly configure Fabric to deal with proxy server and ssh private key file ?
The following should work.
env.key_filename = "./private_openssh.key"
(notice the typo in your attempt)
Fabric's API is best avoided really, way too many bugs and issues (see issue tracker).
You can do what you want in Python with the following:
from __future__ import print_function
from pssh import ParallelSSHClient
from pssh.utils import load_private_key
client = ParallelSSHClient(['host.something.com'],
pkey=load_private_key('private_openssh.key'),
proxy_host='proxyhost',
proxy_port=<proxy port number>,
user='myuser',
proxy_user='myuser')
output = client.run_command('uname')
for line in output['host.something.com'].stdout:
print(line)
ParallelSSH is available from pip as parallel-ssh.
PuTTYgen is what you will use to generate your SSH key then upload the copied SSH key to your Cloud Management portal - See Joyant
You will have to generate and authenticate a private key, to do so, you need PuTTYgen to generate the SSH access using RSA key with password, key comment and conform the key passphrase, here is a step by step guide documentation SSH Access using RSA Key Authentication

What is "principal" argument of kerbros-sspi?

I was trying to connect to remote machine via WinRM in Python (pywinrm) using domain account, following the instruction in
How to connect to remote machine via WinRM in Python (pywinrm) using domain account?
using
session = winrm.Session(server, auth=('user#DOMAIN', 'doesNotMatterBecauseYouAreUsingAKerbTicket'), transport='kerberos')
but I got this:
NotImplementedError("Can't use 'principal' argument with kerberos-sspi.")
I googled "principal argument" and I got its meaning in mathematics,which is in complex_analysis (https://en.m.wikipedia.org/wiki/Argument_(complex_analysis)) and definitely not the right meaning. I'm not a native English speaker and I got stuck here.
The original code is here:
https://github.com/requests/requests-kerberos/blob/master/requests_kerberos/kerberos_.py
def generate_request_header(self, response, host, is_preemptive=False):
"""
Generates the GSSAPI authentication token with kerberos.
If any GSSAPI step fails, raise KerberosExchangeError
with failure detail.
"""
        # Flags used by kerberos module.
        gssflags = kerberos.GSS_C_MUTUAL_FLAG | kerberos.GSS_C_SEQUENCE_FLAG
        if self.delegate:
            gssflags |= kerberos.GSS_C_DELEG_FLAG
        try:
            kerb_stage = "authGSSClientInit()"
            # contexts still need to be stored by host, but hostname_override
            # allows use of an arbitrary hostname for the kerberos exchange
            # (eg, in cases of aliased hosts, internal vs external, CNAMEs
            # w/ name-based HTTP hosting)
            kerb_host = self.hostname_override if self.hostname_override is not None else host
            kerb_spn = "{0}#{1}".format(self.service, kerb_host)
            
            kwargs = {}
            # kerberos-sspi: Never pass principal. Raise if user tries to specify one.
            if not self._using_kerberos_sspi:
                kwargs['principal'] = self.principal
            elif self.principal:
                raise NotImplementedError("Can't use 'principal' argument with kerberos-sspi.")
Any help will be greatly appreciated.

Categories