0

I wanted to create an installation script for my raspberry pi which secures the default installation by configuring/hardening ssh, installing a firewall and fail2ban and finally to get rid off the default user of Raspbian. All other parts work but the final part always shows me an error. The new user is created and added to the sudo group. After that I want to delete the old user 'pi'. As the script runs with sudo in the user context of 'pi' I thought I could solve this by switching to 'su' but I just get an error that the user couldn't be deleted as it is used by a process:

echo "Enter the new user name? Only lower case letters allowed!" 
read user
sudo adduser $user && adduser $user sudo
echo "default user 'pi' will now be deleted"
su -c "deluser -remove-home pi"

If I check with 'users' the user 'pi' is gone but I can still log in with this account. How can I solve this problem inside the script?

I tried the answers I found here: How do I use su to execute the rest of the bash script as that user? and here: https://unix.stackexchange.com/questions/361327/how-to-login-as-different-user-inside-shell-script-and-execute-a-set-of-commands but nothing seem to work. I searched Google but I can't find any solution that works. Is it even possible what I'm trying to?

  • `users` lists currently logged in users. It does not say anything about who can and can't log in. Are you sure the `su -c "deluser -remove-home pi"` succeeded without errors? – that other guy Feb 13 '20 at 22:07
  • No, that's the point. The last line su -c "deluser -remove-home pi" shows the error and pi isn't deleted completely. Only the /home directory is gone but the user still can log in – Coding Noob Feb 14 '20 at 06:57

2 Answers2

0

I usually add set -eux at the beginning of the bash script. This allows to debug and find typos and errors.

Try to switch user inside the script with

sudo -i -u ${user} $(command to delete pi here)
Tarek Dakhran
  • 2,021
  • 11
  • 21
0

Think i found the cause of the problem. 'set -eux' was a great help:

deluser pi
 Removing user `pi' ...
 Warning: group `pi' has no more members.
 userdel: user pi is currently used by process 445
 /usr/sbin/deluser: `/usr/sbin/userdel pi' returned error code 8. Exiting.

I tried ps -fu pi to find the process which causes the trouble: it's /lib/systemd/systemd --user Is there a way to stop this process inside the script?