首页 > 解决方案 > Paramiko 无法访问私钥

问题描述

从 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

该脚本cgi作为supervisord. 任何帮助为什么paramiko不能阅读它?

** 更新 **

看起来我也无法直接从python3 shell打开它 无法打开-ssh-private-key-from-python

但是可以使用绝对路径来完成:

可以打开-ssh-private-key-from-python-absolute-path

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

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

但我不能chdirlistdir它:

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

标签: python-3.xubuntufile-permissionsparamiko

解决方案


正如@MartinPrikryl 正确指出的那样,~找不到。这里

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

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

推荐阅读