Skip to content
Related Articles

Related Articles

Deleting a User in Linux using Python Script
  • Last Updated : 11 May, 2020

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,


Enter Username: John


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.

import os
import subprocess
import sys
import getpass
def delete_user():
     username = input("Enter Username : ")
         output =['userdel', username ])
         if output.returncode == 0:
             print("User successfully deleted with given credentials")
         print(f"Failed to 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.


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.

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up
Recommended Articles
Page :