Paramiko AuthenticationException 问题

发布于 2024-10-01 12:56:37 字数 6905 浏览 3 评论 0原文

我在连接到带有 Paramiko(版本 1.7.6-2)ssh 客户端的设备时遇到问题:

$ python
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import paramiko
>>> ssh = paramiko.SSHClient()
>>> ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
>>> ssh.connect("123.0.0.1", username="root", password=None)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/pymodules/python2.6/paramiko/client.py", line 327, in connect
    self._auth(username, password, pkey, key_filenames, allow_agent, look_for_keys)
  File "/usr/lib/pymodules/python2.6/paramiko/client.py", line 481, in _auth
    raise saved_exception
paramiko.AuthenticationException: Authentication failed.
>>> 

当我从命令行使用 ssh 时,它工作正常:

ssh [email protected]


BusyBox v1.12.1 (2010-11-03 13:18:46 EDT) built-in shell (ash)
Enter 'help' for a list of built-in commands.

# 

有人以前见过这个吗?

编辑 1

以下是 ssh 命令的详细输出:

:~$ ssh -v [email protected]
OpenSSH_5.3p1 Debian-3ubuntu4, OpenSSL 0.9.8k 25 Mar 2009
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: Applying options for *
debug1: Connecting to 123.0.0.1 [123.0.0.1] port 22.
debug1: Connection established.
debug1: identity file /home/waffleman/.ssh/identity type -1
debug1: identity file /home/waffleman/.ssh/id_rsa type -1
debug1: identity file /home/waffleman/.ssh/id_dsa type -1
debug1: Remote protocol version 2.0, remote software version OpenSSH_5.1
debug1: match: OpenSSH_5.1 pat OpenSSH*
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_5.3p1 Debian-3ubuntu4
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: server->client aes128-ctr hmac-md5 none
debug1: kex: client->server aes128-ctr hmac-md5 none
debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<1024<8192) sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_GROUP
debug1: SSH2_MSG_KEX_DH_GEX_INIT sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_REPLY
debug1: Host '123.0.0.1' is known and matches the RSA host key.
debug1: Found key in /home/waffleman/.ssh/known_hosts:3
debug1: ssh_rsa_verify: signature correct
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentication succeeded (none).
debug1: channel 0: new [client-session]
debug1: Requesting [email protected]
debug1: Entering interactive session.
debug1: Sending environment.
debug1: Sending env LANG = en_US.utf8

编辑 2 这是带有调试输出的 python 输出:

Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import paramiko, os
>>> paramiko.common.logging.basicConfig(level=paramiko.common.DEBUG)
>>> ssh = paramiko.SSHClient()
>>> ssh.load_system_host_keys()
>>> ssh.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
>>> ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
>>> ssh.connect("123.0.0.1", username='root', password=None)
DEBUG:paramiko.transport:starting thread (client mode): 0x928756cL
INFO:paramiko.transport:Connected (version 2.0, client OpenSSH_5.1)
DEBUG:paramiko.transport:kex algos:['diffie-hellman-group-exchange-sha256', 'diffie-hellman-group-exchange-sha1', 'diffie-hellman-group14-sha1', 'diffie-hellman-group1-sha1'] server key:['ssh-rsa', 'ssh-dss'] client encrypt:['aes128-cbc', '3des-cbc', 'blowfish-cbc', 'cast128-cbc', 'arcfour128', 'arcfour256', 'arcfour', 'aes192-cbc', 'aes256-cbc', '[email protected]', 'aes128-ctr', 'aes192-ctr', 'aes256-ctr'] server encrypt:['aes128-cbc', '3des-cbc', 'blowfish-cbc', 'cast128-cbc', 'arcfour128', 'arcfour256', 'arcfour', 'aes192-cbc', 'aes256-cbc', '[email protected]', 'aes128-ctr', 'aes192-ctr', 'aes256-ctr'] client mac:['hmac-md5', 'hmac-sha1', '[email protected]', 'hmac-ripemd160', '[email protected]', 'hmac-sha1-96', 'hmac-md5-96'] server mac:['hmac-md5', 'hmac-sha1', '[email protected]', 'hmac-ripemd160', '[email protected]', 'hmac-sha1-96', 'hmac-md5-96'] client compress:['none', '[email protected]'] server compress:['none', '[email protected]'] client lang:[''] server lang:[''] kex follows?False
DEBUG:paramiko.transport:Ciphers agreed: local=aes128-ctr, remote=aes128-ctr
DEBUG:paramiko.transport:using kex diffie-hellman-group1-sha1; server key type ssh-rsa; cipher: local aes128-ctr, remote aes128-ctr; mac: local hmac-sha1, remote hmac-sha1; compression: local none, remote none
DEBUG:paramiko.transport:Switch to new keys ...
DEBUG:paramiko.transport:Trying discovered key b945197b1de1207d9aa0663f01888c3c in /home/waffleman/.ssh/id_rsa
DEBUG:paramiko.transport:userauth is OK
INFO:paramiko.transport:Authentication (publickey) failed.
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/pymodules/python2.6/paramiko/client.py", line 327, in connect
    self._auth(username, password, pkey, key_filenames, allow_agent, look_for_keys)
  File "/usr/lib/pymodules/python2.6/paramiko/client.py", line 481, in _auth
    raise saved_exception
paramiko.AuthenticationException: Authentication failed.
>>> 

I am having a problem connecting to a device with a Paramiko (version 1.7.6-2) ssh client:

$ python
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import paramiko
>>> ssh = paramiko.SSHClient()
>>> ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
>>> ssh.connect("123.0.0.1", username="root", password=None)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/pymodules/python2.6/paramiko/client.py", line 327, in connect
    self._auth(username, password, pkey, key_filenames, allow_agent, look_for_keys)
  File "/usr/lib/pymodules/python2.6/paramiko/client.py", line 481, in _auth
    raise saved_exception
paramiko.AuthenticationException: Authentication failed.
>>> 

When I use ssh from the command line, it works fine:

ssh [email protected]


BusyBox v1.12.1 (2010-11-03 13:18:46 EDT) built-in shell (ash)
Enter 'help' for a list of built-in commands.

# 

Anyone seen this before?

Edit 1

Here is the verbose output of the ssh command:

:~$ ssh -v [email protected]
OpenSSH_5.3p1 Debian-3ubuntu4, OpenSSL 0.9.8k 25 Mar 2009
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: Applying options for *
debug1: Connecting to 123.0.0.1 [123.0.0.1] port 22.
debug1: Connection established.
debug1: identity file /home/waffleman/.ssh/identity type -1
debug1: identity file /home/waffleman/.ssh/id_rsa type -1
debug1: identity file /home/waffleman/.ssh/id_dsa type -1
debug1: Remote protocol version 2.0, remote software version OpenSSH_5.1
debug1: match: OpenSSH_5.1 pat OpenSSH*
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_5.3p1 Debian-3ubuntu4
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: server->client aes128-ctr hmac-md5 none
debug1: kex: client->server aes128-ctr hmac-md5 none
debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<1024<8192) sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_GROUP
debug1: SSH2_MSG_KEX_DH_GEX_INIT sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_REPLY
debug1: Host '123.0.0.1' is known and matches the RSA host key.
debug1: Found key in /home/waffleman/.ssh/known_hosts:3
debug1: ssh_rsa_verify: signature correct
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentication succeeded (none).
debug1: channel 0: new [client-session]
debug1: Requesting [email protected]
debug1: Entering interactive session.
debug1: Sending environment.
debug1: Sending env LANG = en_US.utf8

Edit 2
Here is the python output with debug output:

Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import paramiko, os
>>> paramiko.common.logging.basicConfig(level=paramiko.common.DEBUG)
>>> ssh = paramiko.SSHClient()
>>> ssh.load_system_host_keys()
>>> ssh.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
>>> ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
>>> ssh.connect("123.0.0.1", username='root', password=None)
DEBUG:paramiko.transport:starting thread (client mode): 0x928756cL
INFO:paramiko.transport:Connected (version 2.0, client OpenSSH_5.1)
DEBUG:paramiko.transport:kex algos:['diffie-hellman-group-exchange-sha256', 'diffie-hellman-group-exchange-sha1', 'diffie-hellman-group14-sha1', 'diffie-hellman-group1-sha1'] server key:['ssh-rsa', 'ssh-dss'] client encrypt:['aes128-cbc', '3des-cbc', 'blowfish-cbc', 'cast128-cbc', 'arcfour128', 'arcfour256', 'arcfour', 'aes192-cbc', 'aes256-cbc', '[email protected]', 'aes128-ctr', 'aes192-ctr', 'aes256-ctr'] server encrypt:['aes128-cbc', '3des-cbc', 'blowfish-cbc', 'cast128-cbc', 'arcfour128', 'arcfour256', 'arcfour', 'aes192-cbc', 'aes256-cbc', '[email protected]', 'aes128-ctr', 'aes192-ctr', 'aes256-ctr'] client mac:['hmac-md5', 'hmac-sha1', '[email protected]', 'hmac-ripemd160', '[email protected]', 'hmac-sha1-96', 'hmac-md5-96'] server mac:['hmac-md5', 'hmac-sha1', '[email protected]', 'hmac-ripemd160', '[email protected]', 'hmac-sha1-96', 'hmac-md5-96'] client compress:['none', '[email protected]'] server compress:['none', '[email protected]'] client lang:[''] server lang:[''] kex follows?False
DEBUG:paramiko.transport:Ciphers agreed: local=aes128-ctr, remote=aes128-ctr
DEBUG:paramiko.transport:using kex diffie-hellman-group1-sha1; server key type ssh-rsa; cipher: local aes128-ctr, remote aes128-ctr; mac: local hmac-sha1, remote hmac-sha1; compression: local none, remote none
DEBUG:paramiko.transport:Switch to new keys ...
DEBUG:paramiko.transport:Trying discovered key b945197b1de1207d9aa0663f01888c3c in /home/waffleman/.ssh/id_rsa
DEBUG:paramiko.transport:userauth is OK
INFO:paramiko.transport:Authentication (publickey) failed.
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/pymodules/python2.6/paramiko/client.py", line 327, in connect
    self._auth(username, password, pkey, key_filenames, allow_agent, look_for_keys)
  File "/usr/lib/pymodules/python2.6/paramiko/client.py", line 481, in _auth
    raise saved_exception
paramiko.AuthenticationException: Authentication failed.
>>> 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

烟酉 2024-10-08 12:56:37

这确实是一个古老而遥远的问题,但我刚刚遇到了同样的错误,我认为列出以下信息会很有帮助:

  1. 我正在使用 paramiko 2.9.1 和 python>=3.6,请确保您的 paramiko>=2.9 .0
  2. cmd ssh 工作正常
  3. 下面的代码出现错误:AuthenticationException:身份验证失败。
import paramiko
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
session = client.connect("<hostname>")

从这里 https://github.com/paramiko/paramiko/issues/1984,我知道这是与身份验证算法相关的错误。

您需要在 connect() 中添加 disabled_algorithms 参数,请参阅此处的文档:https://www.paramiko.org/changelog.html#2.9.0

但是2.9.0的changelog有一个disabled_algorithms的拼写错误,应该是:

client.connect("<hostname>", disabled_algorithms={'pubkeys': ['rsa-sha2-256', 'rsa-sha2-512']})

而不是:

client.connect("<hostname>", disabled_algorithms={'keys': ['rsa-sha2-256', 'rsa-sha2-512']})

最后,一切顺利。

附:
刚刚收到错误 无法就用于签署 'ssh-rsa' 密钥的 pubkey 算法达成一致! 对于其他主机,可能将 paramiko 降级到 2.9.0 以下是更好的方法。

It's really a old and remote issue, but I just got the same error and I think It'll be helpful to list the following info:

  1. I'm using paramiko 2.9.1 and python>=3.6, make sure your paramiko>=2.9.0
  2. cmd ssh <hostname> works fine
  3. Code below get error: AuthenticationException: Authentication failed.
import paramiko
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
session = client.connect("<hostname>")

From here https://github.com/paramiko/paramiko/issues/1984, I know this is a bug related to auth algorithms.

You'll need to add a disabled_algorithms param in connect(), see docs here: https://www.paramiko.org/changelog.html#2.9.0

But the changelog of 2.9.0 has a typo for disabled_algorithms, it should be:

client.connect("<hostname>", disabled_algorithms={'pubkeys': ['rsa-sha2-256', 'rsa-sha2-512']})

instead of:

client.connect("<hostname>", disabled_algorithms={'keys': ['rsa-sha2-256', 'rsa-sha2-512']})

Finally, all goes well.

Ps:
Just got error Unable to agree on a pubkey algorithm for signing a 'ssh-rsa' key! for other hosts, may be downgrade paramiko below 2.9.0 is a better way.

双马尾 2024-10-08 12:56:37

远程设备上的 ssh 服务器拒绝了您的身份验证。确保您使用的密钥正确,公钥存在于 authorized_keys 中,.ssh 目录权限正确,authorized_keys 权限正确,并且该设备没有任何其他访问限制。如果没有来自服务器的日志,很难说发生了什么。

[编辑] 我刚刚回顾了您的输出,您正在使用 None 身份验证进行身份验证。这通常是不允许的,用于确定服务器允许哪些身份验证方法。您的服务器可能正在使用基于主机的身份验证(或根本没有!)。

由于 auth_none() 很少使用,因此无法从 SSHClient 类访问它,因此您需要直接使用 Transport

transport.auth_none('root') 

The ssh server on the remote device denied your authentication. Make sure you're using the correct key, the public key is present in authorized_keys, .ssh directory permissions are correct, authorized_keys permissions are correct, and the device doesn't have any other access restrictions. It hard to say what's going on without logs from the server.

[EDIT] I just looked back through your output, you are authenticating using None authentication. This usually isn't ever permitted, and is used to determine what auth methods are allowed by the server. It's possible your server is using host based authentication (or none at all!).

Since auth_none() is rarely used, it's not accessible from the SSHClient class, so you will need to use Transport directly.

transport.auth_none('root') 
零崎曲识 2024-10-08 12:56:37

作为对此事的后续跟进,我相信在受限网络的背景下,我遇到了与 waffleman 相同的问题。

关于在 Transport 对象上使用 auth_none 的提示非常有帮助,但我发现自己对如何实现它有点困惑。问题是,至少到今天为止,在连接之前我无法获取 SSHClient 对象的 Transport 对象;但它一开始就无法连接...

所以,如果这对其他人有用,我的解决方法如下。我只是重写 _auth 方法。

好吧,这很脆弱,因为 _auth 是私有的。我的其他选择是 - 实际上仍然是 - 手动创建 TransportChannel 对象,但目前我觉得我的情况仍然要好得多在引擎盖下。

from paramiko import SSHClient, BadAuthenticationType

class SSHClient_try_noauth(SSHClient):

    def _auth(self, username, *args):
        try:
            self._transport.auth_none(username)
        except BadAuthenticationType:
            super()._auth(username, *args)

As a very late follow-up on this matter, I believe I was running into the same issue as waffleman, in a context of a confined network.

The hint about using auth_none on the Transport object turned out quite helpful, but I found myself a little puzzled as to how to implement that. Thing is, as of today at least, I can't get the Transport object of an SSHClient object until it has connected; but it won't connect in the first place...

So In case this is useful to others, my work around is below. I just override the _auth method.

OK, this is fragile, as _auth is a private thing. My other alternatives were - actually still are - to manually create the Transport and Channel objects, but for the time being I feel like I'm much better off with all this still under the hood.

from paramiko import SSHClient, BadAuthenticationType

class SSHClient_try_noauth(SSHClient):

    def _auth(self, username, *args):
        try:
            self._transport.auth_none(username)
        except BadAuthenticationType:
            super()._auth(username, *args)
深爱不及久伴 2024-10-08 12:56:37

确保对公钥和私钥文件(以及可能包含的文件夹)的权限设置为非常严格(即 chmod 600 id_rsa)。事实证明,这是使用文件作为 ssh 密钥所必需的(操作系统?)。从我乐于助人的同事那里发现了这一点:)
另请确保您为给定的 ssh 密钥使用正确的用户名。

Make sure that the permissions on the public and private key files (and possibly the containing folder) are set to very restrictive (i.e. chmod 600 id_rsa). It turns out this is required (by the Operating System?) to use the files as ssh keys. Found this out from my helpful colleague :)
Also make sure that you are using the correct username for the given ssh key.

罪歌 2024-10-08 12:56:37

我收到这个错误:

paramiko.ssh_exception.AuthenticationException:身份验证失败:传输关闭或看到 EOF

,但当我添加此参数时解决look_for_keys=False

ssh.connect(主机名='主机名',端口=端口,用户名='用户',密码='密码',look_for_keys=False)

I got this error :

paramiko.ssh_exception.AuthenticationException: Authentication failed: transport shut down or saw EOF

but solve when I add this parameter look_for_keys=False

ssh.connect(hostname='hostname',port=port,username='user',password='password',look_for_keys=False)

会傲 2024-10-08 12:56:37

服务器端(您连接到的 sshd)可能有不同的原因,因此可能很难在客户端进行调试。

例如,tail -f /var/log/secure

10 月 9 日 15:50:26 pc1udatahgw04 sshd[27501]:身份验证被拒绝:错误
目录 /home/testuser 的所有权或模式

如果您运行 ls -lad /home/testuser 来查看权限,您将在我们的例子中看到:

$ ls -lad /home/testuser
drwxrwxr-x 16 testuser  testgroup 57344 Oct  9 15:23 /home/testuser

注意第二个 w少量。主目录已打开用于组写入。在这种情况下,sshd 拒绝基于密钥的身份验证。

再次检查服务器端的 sshd 日志。可能还有其他问题,例如已经提到的

  • /home/user/.ssh 目录太打开
  • /home/user/.ssh/id_rsa 文件太打开
  • /home/user/.ssh/id_rsa.pub 文件太打开
  • /home/ user/.ssh/id_ecdsa 文件太打开
  • /home/user/.ssh/id_ecdsa.pub 文件太打开

等等。

There could be different reasons on server side (sshd where you're connecting to), so it might be hard to debug on client side.

For example, tail -f /var/log/secure :

Oct 9 15:50:26 pc1udatahgw04 sshd[27501]: Authentication refused: bad
ownership or modes for directory /home/testuser

If you run ls -lad /home/testuser to see permissions, you'll see for example in our case:

$ ls -lad /home/testuser
drwxrwxr-x 16 testuser  testgroup 57344 Oct  9 15:23 /home/testuser

Notice second w bit. Home directory was opened up for group writes. sshd refuses key based authentication in this case.

Again, check sshd log on server side. There could be other issues like already mentioned

  • /home/user/.ssh directory is too open
  • /home/user/.ssh/id_rsa file is too open
  • /home/user/.ssh/id_rsa.pub file is too open
  • /home/user/.ssh/id_ecdsa file is too open
  • /home/user/.ssh/id_ecdsa.pub file is too open

etc..

荒人说梦 2024-10-08 12:56:37

您可能需要检查服务器的登录情况,尝试执行 tail -f /var/log/auth.log 然后您可能会找到服务器拒绝您连接的原因。
如果服务器显示如下 userauth_pubkey: unsupported public key Algs: rsa-sha2-512 [preauth],那么您可以添加 transport.server_extensions = {'server-sig-algs': 'ssh -rsa'} 初始化传输后

you may need to check log in server, try to excute tail -f /var/log/auth.log then you may find the reason why server refuses your connection.
If server shows like this userauth_pubkey: unsupported public key algorithm: rsa-sha2-512 [preauth], then you can add transport.server_extensions = {'server-sig-algs': 'ssh-rsa'} after you initialize your transport

你是我的挚爱i 2024-10-08 12:56:37

paramiko 的 SSHClientload_system_host_keys 方法,您可以使用该方法加载用户特定的密钥集。正如文档中的示例所解释的,它需要在连接到服务器之前运行。

paramiko's SSHClient has load_system_host_keys method which you could use to load user specific set of keys. As example in the docs explain, it needs to be run before connecting to a server.

怂人 2024-10-08 12:56:37

当服务器使用 AD 身份验证时,我收到类似的错误。我认为这是paramiko的一个错误。我了解到在使用 paramiko 之前必须设置 ssh 密钥。

I get similar error, when the server uses AD authentication. I think this is a bug of paramiko. I have learned that I have to set ssh keys before use paramiko.

没︽人懂的悲伤 2024-10-08 12:56:37

venv 安装还会生成全局文件

在 venv 中安装 paramiko 会在 venv 和全局环境中安装文件。仅在该 venv 中使用 paramiko 似乎不起作用。

在 codium / vscode 中,位于无法访问 venv 的文件夹中,然后在基础环境中使用 paramiko。如果从 venv 卸载它,基本环境将不再运行 paramiko。

从所有这些看来,最好在基本环境中安装 paramiko,以便它也可用于任何 venv。

venv 中的详细

安装会导致全局文件如下就

我而言,只有当我位于虚拟环境 (venv) 中或位于包含 venv 的文件夹中,但激活了基本环境的 Python 解释器时,才会弹出此错误:

>>> ssh.connect(host, port=port, username=user, key_filename=key_filepath)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/MY_USER/Documents/MY_PROJECT/MY_VENV/lib/python3.8/site-packages/paramiko/client.py", line 435, in connect
    self._auth(
  File "/home/MY_USER/Documents/MY_PROJECT/MY_VENV/lib/python3.8/site-packages/paramiko/client.py", line 766, in _auth
    raise saved_exception
  File "/home/MY_USER/Documents/MY_PROJECT/MY_VENV/lib/python3.8/site-packages/paramiko/client.py", line 742, in _auth
    self._transport.auth_publickey(username, key)
  File "/home/MY_USER/Documents/MY_PROJECT/MY_VENV/lib/python3.8/site-packages/paramiko/transport.py", line 1634, in auth_publickey
    return self.auth_handler.wait_for_response(my_event)
  File "/home/MY_USER/Documents/MY_PROJECT/MY_VENV/lib/python3.8/site-packages/paramiko/auth_handler.py", line 258, in wait_for_response
    raise e
paramiko.ssh_exception.AuthenticationException: Authentication failed.

下面的脚本仅在以下情况下才起作用 :我在代码编辑器中加载了任何文件夹作为项目文件夹,该文件夹中没有安装了 Paramiko 的 venv。

from os import getenv
import paramiko
from dotenv import load_dotenv

load_dotenv(MY_FULL_PATH, override=True)

ssh = paramiko.SSHClient()
# ssh.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
host = getenv("MY_HOST")
port = getenv("MY_PORT")
user = getenv("MY_USER")
key_filepath = getenv("MY_SSH_KEY_FILEPATH")
ssh.connect(host, port=port, username=user, key_filename=key_filepath)
sftp = ssh.open_sftp()
sftp.put(MY_FILEPATH1, MY_FILEPATH2)

一旦项目文件夹中存在安装了 Paramiko 的 venv,Paramiko 似乎默认使用 venv,并且即使您选择基本环境作为解释器也会弹出该错误。

我只能猜测这是当 Paramiko 同时安装在基础环境和 venv 中时出现的问题,就像我的情况一样,尽管我安装在 venv 中。

从基本环境卸载

当我尝试从基本环境中卸载它时,它没有找到任何文件:

pip3 uninstall paramiko
Found existing installation: paramiko 2.6.0
Not uninstalling paramiko at /usr/lib/python3/dist-packages, outside environment /usr
Can't uninstall 'paramiko'. No files were found to uninstall.

尽管如此,我在搜索 时在 ./lib/python3/dist-packages/ 找到它grep -lR paramiko /usr.我也有两个版本。我的猜测是 Paramiko 无法处理 venv 中的安装,因为当您不在 venv 中时它仍然可以成功使用。如果您所在的文件夹可以访问实际安装了它的 venv,则除非您再次卸载它(已测试),否则它将无法工作。导致错误的 venv 是一个全新的设置,因为我在另一个现有的 venv 中安装 Paramiko 时遇到问题。解决方案是从 venv 中卸载它,然后我可以使用 venv 并从全局安装中获取 Paramiko,可能是因为全局安装由 venv 安装主导,然后又错误地与全局安装交织在一起。

从 venv 卸载

当我从 venv 卸载它时,在基本环境中不再找到 paramiko。

我还发现,如果您想在 venv 中运行命令,在 venv 中使用 Paramiko 需要一些额外的步骤,也许这解释了 Paramiko 通常是全局安装?请参阅使用 Paramiko SSH 设置 virtualenv

欢迎任何进一步的想法。

venv installation also makes global files

Installing paramiko in a venv installs files both in the venv and in the global environment. Using paramiko in that venv only does not seem to work.

In codium / vscode, be in a folder that has no access to the venv and then use paramiko in the base environment. If you uninstall it from the venv, the base environment does not run paramiko anymore.

From all of this it seems best to install paramiko only in the base environment so that it is available for any venv as well.

Details

installation in the venv leads to global files as well

In my case, this error only popped up when I was in a virtual environment (venv) or when I was in a folder that contained a venv as well, but with Python interpreter of the base environment activated:

>>> ssh.connect(host, port=port, username=user, key_filename=key_filepath)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/MY_USER/Documents/MY_PROJECT/MY_VENV/lib/python3.8/site-packages/paramiko/client.py", line 435, in connect
    self._auth(
  File "/home/MY_USER/Documents/MY_PROJECT/MY_VENV/lib/python3.8/site-packages/paramiko/client.py", line 766, in _auth
    raise saved_exception
  File "/home/MY_USER/Documents/MY_PROJECT/MY_VENV/lib/python3.8/site-packages/paramiko/client.py", line 742, in _auth
    self._transport.auth_publickey(username, key)
  File "/home/MY_USER/Documents/MY_PROJECT/MY_VENV/lib/python3.8/site-packages/paramiko/transport.py", line 1634, in auth_publickey
    return self.auth_handler.wait_for_response(my_event)
  File "/home/MY_USER/Documents/MY_PROJECT/MY_VENV/lib/python3.8/site-packages/paramiko/auth_handler.py", line 258, in wait_for_response
    raise e
paramiko.ssh_exception.AuthenticationException: Authentication failed.

The script below worked only when I loaded whatever folder as the project folder in my code editor that did not have a venv with an installed Paramiko in it.

from os import getenv
import paramiko
from dotenv import load_dotenv

load_dotenv(MY_FULL_PATH, override=True)

ssh = paramiko.SSHClient()
# ssh.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
host = getenv("MY_HOST")
port = getenv("MY_PORT")
user = getenv("MY_USER")
key_filepath = getenv("MY_SSH_KEY_FILEPATH")
ssh.connect(host, port=port, username=user, key_filename=key_filepath)
sftp = ssh.open_sftp()
sftp.put(MY_FILEPATH1, MY_FILEPATH2)

As soon as there is a venv with installed Paramiko in the project folder, Paramiko seems to use the venv by default, and that error pops up even if you choose the base environment as the interpreter instead.

I can only guess that this is a problem that occurs when Paramiko is installed both in the base environment and in the venv, as in my case, although I installed it only in the venv.

uninstall from the base env

When I tried uninstalling it from the base environment, it did not find any files:

pip3 uninstall paramiko
Found existing installation: paramiko 2.6.0
Not uninstalling paramiko at /usr/lib/python3/dist-packages, outside environment /usr
Can't uninstall 'paramiko'. No files were found to uninstall.

Still, I find it at ./lib/python3/dist-packages/ when searching grep -lR paramiko /usr. And I have it also in two venvs. My guess is that Paramiko cannot deal with an installation in a venv since it is still successfully used when you are not in the venv. If you are in a folder with access to the venv that actually has it installed, it does not work unless you uninstall it again (tested). The venv that causes the errors is a completely new setup because I had problems installing Paramiko in another existing venv. The solution was to uninstall it from the venv, then I can use the venv and get Paramiko from the global installation, probably because the global installation is dominated by the venv installation which is then again wrongly interwined with the global installation.

uninstall from the venv

When I uninstalled it from the venv, paramiko was not found in the base environment anymore.

I also see that using Paramiko in a venv needs some extra steps if you want to run a command in a venv, perhaps that explains that Paramiko is generally a global installation? See Set up virtualenv with Paramiko SSH.

Any further ideas welcome.

终难遇 2024-10-08 12:56:37

请记住,RSA 在 Ubuntu 22.04 中已被弃用。您应该将算法更改为 id_ed25519。那么您可能需要清理您的known_hosts并再次将您的公钥复制到远程服务器。

Remember, RSA is deprecated in Ubuntu 22.04. you should change your algorithm to id_ed25519. Then probably you need to clean up your known_hosts and copy your public key to the remote server once again.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文