0

I'm working on an industrial application for the Pi, and for that we need to, of course, change the username. I don't want to do this manually everytime, so I want to use a script. So far I have written a script for writing the image to the SD card and an install script that installs all the right dependencies, repositories etc. Now I have had good results changing the username manually based on the answer of Mike Lutz in this question, which states

exec sudo -s
cd /
usermod -l newname -d /home/newname -m oldname

unfortunately, this does not work if you want to use it in a script, because the script will still be running on your old username, and therefor the username can't be changed.

So what I have resorted to now, is in the imaging to SD card script, I have written the following:

NEWNAME=pareto
boot_path=/media/pareto/pi_boot
filesystem_path=/media/pareto/pi_filesystem

#check for mounted sd card => unmount
echo "Unmounting SD card"
sudo umount /dev/mmcblk0p1
sudo umount /dev/mmcblk0p2

# mount SD card partitions to the right folders 
echo "Mounting SD card partitions"
sudo mount -t vfat /dev/mmcblk0p1 $boot_path
sudo mount -t ext4 /dev/mmcblk0p2 $filesystem_path

# replace username 'pi' with '$NEWNAME'
echo "Replacing all instances of user 'pi' with '$NEWNAME'"
for i in passwd shadow group gshadow sudoers; do
sudo sed -i "s/:pi/:$NEWNAME/g" $filesystem_path/etc/$i
sudo sed -i "s/^pi:/$NEWNAME:/g" $filesystem_path/etc/$i
sudo sed -i "s/\/pi:/\/$NEWNAME:/g" $filesystem_path/etc/$i
done

# change the home folders name to correspond with $NEWNAME 
sudo mv $filesystem_path/home/pi $filesystem_path/home/$NEWNAME

So far it seems to work, but it feels very dirty. Is there a better way to change the username from a script (either via SSH/UART console) and if not, am I missing some important files I should change as well?

F. Pareto
  • 191
  • 1
  • 5

1 Answers1

2

If I wanted to do this (and I still think it is futile - pi is just a text label for user 1000, and the number can be used in many contexts), I wouldn't do it on a working system.

AFAIK the string pi only appears in 3 places; /etc/passwd, /etc/group and a directory in /home. I would just edit in the appropriate files on a mounted image. (I haven't actually done this so it may need testing.)

Milliways
  • 62,573
  • 32
  • 113
  • 225