How to delete a user in Linux using Python

Python has a vast collection of modules for computing ranging from basic operations like a square root to image processing. One such module is os, which is for using operating system dependent functionalities in any Python script. When a computer is shared, to customize each user’s experience, user accounts are created. In Linux, adding and removing user accounts can be done with either command line or GUI. The command for adding a user in Linux would be

sudo adduser username

where username is the name of the user.
Python’s os module has a method called system() which takes the command to be run as the parameter and executes it. The method system() has the signature

os.system(command)

A Python program to remove a user would be

import os
name = input("Username: ")
choice = input("Keep home directory? [Y/n]")
if choice == 'n':
    os.system("sudo deluser --remove-home "+name)
    print("User deleted")
else:
    os.system("sudo deluser "+name)
    print("User deleted")

This program accepts the username of the user to be removed and the choice whether or not to keep the user’s home directory and then removes the user. Invoking this method actually invokes the C system call system() in a subshell. So whatever the system call should print would be printed in the command line.
For instance,  consider two users user1 and user2 and create them. The list of users can be found with command ls /home.

$ ls /home 
current_user user1 user2

The program is run twice, once for deleting a user. In this demonstration, user1’s home directory is also removed, whereas, for user2 the home directory is kept.

$ python3 removeuser.py
Username: user1 
Keep home directory? [Y/n]n 
Looking for files to backup/remove ... 
Removing files ... 
Removing user `user1' ... 
Warning: group `user1' has no more members. Done. 
User deleted
$ su user1 
No passwd entry for user 'user1'

The command su username will switch current working directory to the directory specified by username if such user account exists.

$ python3 removeuser.py 
Username: user2 
Keep home directory? [Y/n]Y 
Removing user `user2' ... 
Warning: group `user2' has no more members. Done. 
User deleted
$ su user2 
No passwd entry for user 'user2'
$ ls /home 
current_user user2

Both the users, user1 and user2 have been deleted. But while deleting user2, --remove-home was not specified. As a result, user2 alone is in the /home directory.

Leave a Reply

Your email address will not be published.