3
2

More than 3 years have passed since last update.

ec2などでssh-copy-idコマンドが失敗する時の新規ユーザと認証鍵の設定

Last updated at Posted at 2020-03-11

いろんなところで見かける ssh-copy-id コマンドだけど...

パスワード認証など、他の認証手段が有効な時にしか使えないのですよね。
こんなエラーが出ちゃいます:

ssh-copy-id -i ~/.ssh/key_taiyo.pub taiyo@remote.site
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/Users/taiyo/.ssh/key_taiyo.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
taiyo@remote.site: Permission denied (publickey).

AWSのec2やlightsailなど、デフォルトで .pem 認証鍵しか手段が無い場合は、別の方法が必要です。
つても手動でちょいちょい書いてあげるだけ。カンタンですよ。

大まかな流れ: 下準備 〜 リモートに設置 〜 sshd再起動

ローカルマシンでキーペアを作成
リモートにユーザ作成
ユーザの~.sshフォルダを作成
公開鍵を設置
sshd 再起動

前準備:

#前準備:ローカルマシン側でキーペアを作成
ssh-keygen -f ~/.ssh/key_taiyo -t ed25519

##前準備:ローカルマシン側でキーファイルを登録
ssh-add ~/.ssh/key_taiyo

##前準備:公開鍵の中身を確認 (のちほど ssh でリモート側に転記)
cat ~/.ssh/key_taiyo.pub

# 注意: ssh-copy-id コマンドは一度pw認証が必要で脆弱なのでネット越しに使わない。
# "一時的に PasswordAuthentication yes" する手法がググると出てくるが、それは非推奨。

リモート側にて

#ユーザー作成
adduser taiyo

#ユーザーにスイッチ
su taiyo

# .ssh を設置
mkdir ~/.ssh

#このファイルに、.pub の中身をそのままペースト
nano ~/.ssh/authorized_keys

# sshd をリスタート
sudo systemctl restart sshd
# もしエラーが出たら、パーミッションの設定が必要かも
chmod 700 ~/.ssh
chmod 600 ~/.ssh/*

これで任意のユーザー・キーペアでリモートログインが可能に。

デフォルトのubuntuユーザーは殺しても良いです。
後はsudoerへの追加など、作業に合わせて設定しましょう。

作業者の環境は MacOS 10.15.3、リモートはUbuntu18.04ですが、大概の*nixで共通だと思います。

3
2
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
3
2