With the following snippet of a script to add new users each user gets a public\private key pair automatically created, with the private key in their home directory for winscping out. The script works with one problem: authorized_keys always gets the owner root, and group root. Even though I assign the user being added as the owner before and after moving the public key to the authorized_keys file. If I rerun the commands manually after the script everything works fine. I am running the script as root. Permissions also appear to set incorrectly. Any ideas?
usermod -g webteam $UNAME
cd /home/$UNAME
ssh-keygen -b 1024 -t dsa -N $UPASS -f $UNAME"key" > key.log
mkdir .ssh
chown $UNAME $UNAME"key.pub"
chgrp $UNAME $UNAME"key.pub"
mv $UNAME"key.pub" .ssh/authorized_keys
chmod 740 $UNAME"key"
chown $UNAME $UNAME"key"
chown $UNAME .ssh
echo "PYTHONPATH=/usr/local/lib/python2.4/site-packages" >> .ssh/environment
chown $UNAME .ssh/*
chgrp $UNAME .ssh/*
chmod 700 .ssh/*
chmod 750 .ssh