LoginSignup
1
3

More than 5 years have passed since last update.

サーバーにユーザーを追加する時にたまーーーーーーに使うスクリプトを置いておく

Posted at

基本的にこんなスクリプトを使う時代じゃぁありませんが、、、

AWS とか使うようになってから、ユーザーを追加するなんて事は基本していないですけど、
前から使ってる VPS でうんちゃらする必要が出て他の人を追加したするようにスクリプトを書いたので備忘録として。
sudo 権限が必要なうろ覚えのコマンドを直打ちするのは怖すぎるので、スクリプトを書いておくと安心。

createuser.sh
#!/bin/bash -e

usage() {
        echo "$0 <user> [group]"
}

if [ $# -lt 1 ]; then
        usage
        exit 1
fi

readonly user=$1
readonly group=${2:-$user}

echo "# User information #"
echo "user: $user"
echo "group: $group"
echo -n "Are you sure to make this user? [y/N] "
read yn

case $yn in
        y|Y|yes|Yes|YES) ;;
        *) echo "Aborting..." && exit 2 ;;
esac

goption="-g $group"
if [ "$user" == "$group" ]; then
        goption="--user-group"
fi

echo "# Command information #"
echo "Here is the command to run. Are you really sure to continue?"
echo "useradd --create-home $goption $user"
echo -n "[y/N] "
read yn

case $yn in
        y|Y|yes|Yes|YES) ;;
        *) echo "Aborting..." && exit 2 ;;
esac

useradd --create-home $goption $user
grant.sh
#!/bin/bash

usage() {
        echo "$0 <user>"
}

if [ $# -lt 1 ]; then
        usage
        exit 1
fi

user=$1
echo "# User information #"
echo "user: $user"
echo -n "Are you sure to grant wheel permission to this account? [y/N]"
read yn

case $yn in
        y|Y|yes|Yes|YES) ;;
        *) echo "Aborting..." && exit 2 ;;
esac

usermod --append --groups wheel $user

ええ、そうです。CentOS です。なにか?

sshkey.sh
#!/bin/bash -e

usage() {
        local u=${1:-<user>}
        local pk=${2:-<public-key>}
        echo "This script assume your home directory is /home/$u"
        echo "$0 $u \"$pk\""
        echo "NOTE: You need to quote your public key"
}

if [ $# -lt 2 ]; then
        usage $@
        exit 1
fi

user=$1
publickey=$2
echo "# User information #"
echo "user: $user"
echo -n "Are you sure to set public key to this user? [y/N] "
read yn

case $yn in
        y|Y|yes|Yes|YES) ;;
        *) echo "Aborting..." && exit 2 ;;
esac

readonly sshdir=/home/$user/.ssh
if [ ! -d $sshdir ]; then
        echo "Making directory"
        mkdir $sshdir
        chown -R $user $sshdir
fi

readonly authfile=$sshdir/authorized_keys
touch $authfile
chmod 600 $authfile
chown -R $user $sshdir

echo "Installing public key to auth file: $authfile"
echo $publickey >>$authfile
echo "This is an installed key: $publickey"
1
3
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
3