ssh公開鍵認証の自動セットアップスクリプトを作った
えっと...ssh root@192.168.0.2
して...パスワードを入力して...が面倒な人のために。
いつもやっている公開鍵認証の設定作業を短縮するため、公開鍵認証を自動でセットアップする。
linuxでも同様のスクリプトを書いたが、今回はpowershellで書く。
ただしlinuxには ssh-copy-id
という便利なコマンドがあるようです。configファイルは書いてくれないけど。
使い方
- 下のps1スクリプトを任意の場所に作成する。
- powershellで実行する。以下のパラメータを実行時または実行中に渡す。
- 実行後、次回以降は
ssh hoge
等hostnameのみssh接続が可能になる。
- 実行の例:
./GiveRSAAuth.ps1 -user root -hostname hoge -ip_addr 192.0.2.1
-
user
パラメータ: 接続先のユーザー名 -
hostname
パラメータ: 接続先のホスト名 -
ip_addr
パラメータ: 接続先のIPアドレス
-
スクリプト
GiveRSAAuth.ps1
# to automatic giving RSA authentication via ssh
# get args
Param( [parameter(mandatory=$true)]$user, [parameter(mandatory=$true)]$hostname, $ip_addr )
# read ssh publilc key from file
$public_key = Get-Content $Home\.ssh\id_rsa.pub
# TODO: herestring's return code has \r
# $ssh_command = @"
# mkdir -m 700 .ssh
# echo "$public_key" >> .ssh/authorized_keys
# "@
# ssh $user@$ip_addr "$ssh_command"
# make .ssh directory to target machine via ssh
ssh $user@$ip_addr "mkdir -m 700 .ssh"
# add ssh publilc key to target machine via ssh
ssh $user@$ip_addr "echo "$public_key" >> .ssh/authorized_keys"
# make config file
$ssh_config = @"
Host $hostname
HostName $ip_addr
User $user
IdentityFile $Home\.ssh\id_rsa
"@
# add host config to ssh config file
Write-Output $ssh_config | Out-File -Append -Encoding utf8 $Home\.ssh\config
課題
- ヒアストリングに\rが挟まり、一回のsshで設定が完了できないため、ヒアストリングの使用を諦めた。