Linuxの1ユーザの複数サーバ分のssh鍵の自動生成
コードブロックに行番号を付加できないかは模索中
ファイル名;create_key.sh
#!/bin/bash
# values
KEYSIZE=2048
# script dir
DIR_BASE=$(cd $(dirname ${0}); pwd)
if [ $# = 0 ] ; then
echo -e "Error: No arguments set"
echo -e "Usage: $0 [user name] [server01:server02:...]"
exit 10
fi
USER=$1
SERVERS=`echo $2 | sed -e 's/:/ /g'`
USERDIR=${DIR_BASE}/${USER}
test ! -d ${USERDIR} && mkdir ${USERDIR}
for server in ${SERVERS}
do
test ! -d ${USERDIR}/${server} && mkdir ${USERDIR}/${server}
passphrase=`cat /dev/urandom | tr -dc 'a-kmnpr-zABD-HJL-NQRPT0-9#?_!' | fold -w 8 | head -n 300 | grep -v '^[#?_!]' | grep '[#?_!]' | grep [0-9] | grep -vE '(.)\1' | shuf -n 1`
keyfile=${USERDIR}/${server}/${USER}
ssh-keygen -f ${keyfile} -t rsa -b ${KEYSIZE} -N ${passphrase}
if [ $? = 0 ] ; then
echo -e "User: ${USER} ,Server: ${server}, Passphrase: [${passphrase}]"
echo -e "## ${server}\nUser:\n${USER}\n\nPassphrase:\n${passphrase}" > ${server}_${USERDIR}/SSHinfo_${USER}.txt
else
echo -e "Couldn't make the key. -User: ${USER} ,Server: ${server}"
fi
done
実行例
$ ./create_key.sh user01 web:mail
引数1
ユーザ名
引数2
サーバ名、複数の場合はサーバ名を: (コロン)で区切る
説明
1. スクリプトファイルと同じディレクトリ階層に作成したい ユーザ名のディレクトリを作成する (実行例:user01)
2. サーバごと以下2-1から2-4を繰り返す
2-1.1番で作1番で作成したユーザディレクトリ配下にサーバ名のディレクトリを作成する (実行例:web)
2-2.パスフレーズをランダムの文字列で生成
2-3.2-2番で生成したパスフレーズをもとに、2-1番で作成したサーバ名のディレクトリに鍵のペアを作成
2-4.1番で作成したユーザ名のディレクトリにサーバ名、ユーザ名、パスフレーズを記載したファイルを作成
2-4で作成したファイル名はSSHinfo_サーバ名_ユーザ名.txt
例 web_SSHinfo_user01.txt
## web
User:
user01
Passphrase:
U4#DvXnH
エラー処理を最小限にしているため、予期せぬ事態に対処できてないかも
課題 (後日記載)
複数ユーザに対応するため、引数にリストファイルを指定することで、複数ユーザの指定サーバごとに鍵を作成する
memo
psslibでのパスワードのハッシュ化
passhash=`python3 -c 'import passlib.hash; print(passlib.hash.sha512_crypt.using(rounds=5000).hash("$passphrase"))'`
echo -e "password hash is [${passhash}] "
echo -e "\npassword hash\n${passhash}" >> ${server}_${USERDIR}/SSHinfo_${USER}.txt
Crieitは誰でも投稿できるサービスです。 是非記事の投稿をお願いします。どんな軽い内容でも投稿できます。
また、「こんな記事が読みたいけど見つからない!」という方は是非記事投稿リクエストボードへ!
こじんまりと作業ログやメモ、進捗を書き残しておきたい方はボード機能をご利用ください。
ボードとは?
コメント