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

6.5k Views Asked by At

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))
4

There are 4 best solutions below

1
On

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.

0
On

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.
1
On

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.

1
On

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