Monday, September 1, 2025
HomeLanguagesAdd a User in Linux using Python Script

Add a User in Linux using Python Script

Creating a user via command line in Linux is a tedious task. Every time someone joins your organization and you need to type a long Linux command rather than doing this you can create a python script that can ask for you the username and password and create that user for you. Examples:

Input : 
Enter Username : John
Password: ****


Output :
User successfully created with given credentials

Below is the Python code – 

Python3




# importing linrary
import os
import subprocess
import sys
import getpass
 
# add user function
def add_user():
 
     # Ask for the input
     username = input("Enter Username ")  
 
     # Asking for users password
     password = getpass.getpass()
        
     try:
         # executing useradd command using subprocess module
         subprocess.run(['useradd', '-p', password, username ])     
     except:
         print(f"Failed to add user.")                    
         sys.exit(1)
 
add_user()


Output:

 user add output 

After successfully creating the user type, use this command to get details of new user –

cat /etc/passwd

useradd

RELATED ARTICLES

Most Popular

Dominic
32251 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6619 POSTS0 COMMENTS
Nicole Veronica
11792 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11841 POSTS0 COMMENTS
Shaida Kate Naidoo
6735 POSTS0 COMMENTS
Ted Musemwa
7016 POSTS0 COMMENTS
Thapelo Manthata
6689 POSTS0 COMMENTS
Umr Jansen
6707 POSTS0 COMMENTS