0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

windowsからlinuxに向けてssh公開鍵認証を自動的に設定する

Posted at

ssh公開鍵認証の自動セットアップスクリプトを作った

えっと...ssh root@192.168.0.2して...パスワードを入力して...が面倒な人のために。

いつもやっている公開鍵認証の設定作業を短縮するため、公開鍵認証を自動でセットアップする。
linuxでも同様のスクリプトを書いたが、今回はpowershellで書く。
ただしlinuxには ssh-copy-id という便利なコマンドがあるようです。configファイルは書いてくれないけど。

使い方

  1. 下のps1スクリプトを任意の場所に作成する。
  2. powershellで実行する。以下のパラメータを実行時または実行中に渡す。
  3. 実行後、次回以降は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で設定が完了できないため、ヒアストリングの使用を諦めた。
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?