【问题标题】:Paramiko can not access private key [duplicate]Paramiko无法访问私钥[重复]
【发布时间】:2025-04-12 21:25:02
【问题描述】:

在从 Ubuntu 18.04 升级发行版之后。到 20.04。

FileNotFoundError: [Errno 2] No such file or directory: '~/.ssh/id_rsa'
Exception in thread Thread-2:
Traceback (most recent call last):
  File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.8/threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "/home/cgi/.local/lib/python3.8/site-packages/distributed/deploy/old_ssh.py", line 50, in async_ssh
    ssh.connect(
  File "/home/cgi/.local/lib/python3.8/site-packages/paramiko/client.py", line 435, in connect
    self._auth(
  File "/home/cgi/.local/lib/python3.8/site-packages/paramiko/client.py", line 676, in _auth
    key = self._key_from_filepath(
  File "/home/cgi/.local/lib/python3.8/site-packages/paramiko/client.py", line 586, in _key_from_filepath
    key = klass.from_private_key_file(key_path, password)
  File "/home/cgi/.local/lib/python3.8/site-packages/paramiko/pkey.py", line 235, in from_private_key_file
    key = cls(filename=filename, password=password)
  File "/home/cgi/.local/lib/python3.8/site-packages/paramiko/rsakey.py", line 55, in __init__
    self._from_private_key_file(filename, password)
  File "/home/cgi/.local/lib/python3.8/site-packages/paramiko/rsakey.py", line 175, in _from_private_key_file
    data = self._read_private_key_file("RSA", filename, password)
  File "/home/cgi/.local/lib/python3.8/site-packages/paramiko/pkey.py", line 307, in _read_private_key_file
    with open(filename, "r") as f:

但它就在那里:

$ cat ~/.ssh/id_rsa
-----BEGIN RSA PRIVATE KEY-----
<no one is so stupid>

权限:

sudo$ ll /home/cgi/.ssh/id_rsa
-rw------- 1 cgi cgi 6363 Jul 29  2019 /home/cgi/.ssh/id_rsa

脚本作为supervisord 的一部分在用户cgi 下运行。为什么paramiko 看不懂有什么帮助吗?

** 更新**

看来我也不能直接从python3 shell打开它

但是可以做到,使用绝对路径

所以看起来 ~ 在 python 环境中没有被解释为我的用户 (cgi)。

> os.path.expanduser("~")
< '/home/cgi'

但我不能chdirlistdir它:

> os.listdir('~')
< FileNotFoundError: [Errno 2] No such file or directory: '~'

【问题讨论】:

  • 你能做到open("~/.ssh/id_rsa", "r")吗? + os.path.expanduser("~") 返回什么?
  • @MartinPrikryl 感谢您的回复。我围绕它做了一些测试并更新了问题。
  • 那么,如果您执行cd ~pwd,您会在shell 中得到什么? + Python os.path.expanduser("~") 怎么样?
  • &gt;&gt;&gt; os.path.expanduser("~") --> /home/cgios.listdir('~') --> No such file or directory: '~'

标签: python-3.x ubuntu file-permissions paramiko


【解决方案1】:

正如@MartinPrikryl 正确指出的那样,找不到~Here

在初始化paramiko 连接之前执行这些命令:

os.environ["HOME"] = "/home/cgi/"
os.path.expanduser("~/.ssh/id_rsa")

【讨论】: