Deleting a User in Linux using Python Script


Deleting a user from your system or server via a python script is a very easy task. You just need to pass the username of the user and the script will remove the details and all the files of that user.This python script uses userdel Linux command to delete the user.You can directly use userdel command if you remember the command but if you don’t then the script makes it easy to delete the user.

The script we are about to build will ask the username of the user to be deleted as follows,

Input:

Enter Username: John

Output:

User successfully deleted with given credentials

Before running the script first we will show the user we want to delete.
cat /etc/paswd will list all the users on your system or server.John is the user we will be deleting.



delete user

The below Python code is the script we will be using for our purpose.

filter_none

edit
close

play_arrow

link
brightness_4
code

import os
import subprocess
import sys
import getpass
  
  
def delete_user():
     username = input("Enter Username : ")
  
     try:
         output = subprocess.run(['userdel', username ])
         if output.returncode == 0:
             print("User successfully deleted with given credentials")
  
     except:
         print(f"Failed to delete user.")
         sys.exit(1)
  
delete_user()

chevron_right


delete_user

After running the script it will prompt for the username we want to delete and after entering the name the same user will be removed from the system.

delete_user

After if we check by typing cat/etc/passwd we can see that the user “John” is no longer on that list. So we have successfully deleted our user.

My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.