LoginSignup
0
0

More than 1 year has passed since last update.

paramiko で known_hosts をちゃんと読む

Posted at

Paramiko でよく見かける not found in known_hosts

PythonでSSHによるリモート接続周りを自動化しようと思うと、paramiko を使うことが多いかと思いますが、
ほぼほぼこちらのエラーと遭遇するのではないでしょうか。

paramiko.ssh_exception.SSHException: Server ‘~~~~~’ not found in known_hosts

今回はこちらに対応してみます。

対応方法1

with paramiko.SSHClient() as ssh:
    ssh.set_missing_host_key_policy(paramiko.WarningPolicy())
    ssh.connect(...)
    ...

よくある、無視しちゃえ、というやり方です。
Google先生に聞くと、こちらの方法がたくさん出ます。

今回は別の方法も見ていきます。

対応方法2

with paramiko.SSHClient() as ssh:
    ssh.load_system_host_keys()
    ssh.connect(...)
    ...

システムのknown_hosts を読ませることで、known_hosts に記録されたホストに関してはエラーが起きずに実行できます。…ですが、自動的に実行しようと思うと、そもそも known_hosts にエントリが無いよ!という状態になりがちです。

そこで…paramiko を利用する前に、次のコマンドで known_hosts を作成します。

touch ~/.ssh/known_hosts
ssh-keygen -R example.com
ssh-keyscan example.com

touch しているのは、初期状態だと known_hosts ファイルが無く、ssh-keygen がエラーとなるためです。
接続先のポートが標準ポート(22)じゃない場合は、次の通り。

touch ~/.ssh/known_hosts
ssh-keygen -R [example.com]:10022
ssh-keyscan -p 10022 example.com

これで、エラーが発生しなくなります。

注意: 上記の方法は無条件に鍵を信じる動きであり、本質的には警告を無視するのと同等の行為です。安心できる接続先に対して利用しましょう。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0