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 –

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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()   4
         
     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()

chevron_right


Output:
user add output

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

cat /etc/passwd

useradd

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.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.