bash script to create user then create ssh keys

George Reith asked:

Please note I am a total linux newbie, please bare that in mind when answering this question as I have very limited knowledge of linux.

OS: Debian Squeeze

I am using ZSH and have created a function called webuseradd it looks like this:

function webuseradd () {
    echo creating user $1;
    mkdir /usr/share/nginx/$1;

    # sshlogin is required to allow user to ssh and sftp
    sudo useradd -G lshell,sshlogin -b /usr/share/nginx/$1/home -d /usr/share/nginx/$1/home -m --skel /etc/httpskel -K UMASK=027 $1;

    # /usr/share/nginx/$1 will be the chroot so set it to root
    sudo chown root:root /usr/share/nginx/$1;
    sudo su - $1;
    mkdir /usr/share/nginx/$1/home/.ssh;
    ssh-keygen -t rsa;

    # force the user into a limited, jailed shell
    sudo chsh -s /usr/bin/lshell $1;

However if I call it this it the output I get:

$ webuseradd test
creating user test
No directory, logging in with HOME=/

The user is created fine however the issue arises when I attempt to su into the user. If I exit the script then continues with the following output:

Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):

How do I ensure the keys get created and put in the correct location with the correct permissions within the function? I’m sure there are some other things I have done that are inadvisable so if you spot anything please say.

My answer:

If you’re running this function as root, there’s no need to call su and then run several commands. Besides, that won’t work anyway. You’ll just get an interactive shell, and then the script will continue when you exit that shell.

Just run the commands you need with sudo directly: (and you don’t need mkdir; ssh-keygen will do that for you)

sudo -u $1 -- ssh-keygen -t rsa

View the full question and answer on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.