1
1

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.

Linux ユーザ作成&鍵作成シェルスクリプト

Last updated at Posted at 2018-05-31

# Linux ユーザ作成&鍵作成シェルスクリプト

毎回ユーザ作って、鍵設定してってのは面倒だったのでスクリプトを作成しました。
Ubuntu16 CentOS6,7で動作しているのは確認済み

鍵のパスフレーズなし、ユーザのパスワードも無しなので、SSH設定で鍵認証のみにする事をお勧めします。

#!/usr/bin/env /bash
set -eu
TODAY=`date "+%Y%m%d_%H-%M-%S"`
HOSTNAME=`hostname -s`
CURDIR=`dirname $0`
if [ -e ${CIRDIR}/log ]; then
    mkdir -p ${CIRDIR}/log
fi
echo "${TODAY} : user :$1 ">> ${CURDIR}/log/adduser.log

if [ "`cat /etc/passwd | grep ${1}`" = "" ]; then
    echo "## useradd $1"
    useradd $1
else
    echo "## user $1 already exists. skip useradd"
fi
if [ "`cat /etc/passwd | grep ${1} | awk -F: '{print $7}'`" = "" ]; then
    echo "## setting loginshell"
    sed -i '/'${1}':x:/ s/$/\/bin\/bash/' /etc/passwd
else
    echo "## already loginshell setting. skip"
fi

mkdir -p /home/${1}/.ssh
chmod 700 /home/${1}/.ssh
if [ -f /home/$1/.ssh/${HOSTNAME}-$1 ]; then
    echo "## ssh key already exists"
else
    echo "## ssh key generate"
    ssh-keygen -f /home/${1}/.ssh/${HOSTNAME}-${1} -t rsa -N ""
    sed -i 's/root/'${1}'/' /home/${1}/.ssh/${HOSTNAME}-${1}.pub
    cat /home/${1}/.ssh/${HOSTNAME}-${1}.pub >>/home/${1}/.ssh/authorized_keys
fi
chown -R ${1}.${1} /home/${1}
cp -p /home/${1}/.ssh/${HOSTNAME}-${1} ${CURDIR}/log/

echo "## display $1 privatekey"
cat /home/${1}/.ssh/${HOSTNAME}-${1}

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?