Create temporary User on Linux Host

Introduction

The following script will help you to create a temporary user on the host and delete all the content associated with the user after 3 hours. These scenario will be working incase if a user wants to access the hosts for sometime, troubleshoot issues, verify logs, etc., Replace variable with appropriate values. This has been tested on Centos 6 and its working fine. Use at your own risk :P.

Prerequisites

  1. Centralized box which has access to all production servers.
  2. All the requested python module installed.
  3. User needs to be deleted after 3 hours

Implementation:

  1. Passing username and hosts as variables while executing the script.
  2. Create Temporary user on the host with random password
  3. Send Notifications to recipient email address about user creation.
  4. Create a temporary file on the remote host to delete the user from the host.
  5. Add the temporary file to cron to delete the user after 3 hours(in our case)
  6. Delete the cron entry and user after 3 hours
#!/usr/bin/env python
#########Fab file to Create Temporary User########
#Author:Dhanasekaran N
#Email:support@pheonixsolutions.com
#Version:0.1
##################################################
from fabric.api import env, run
from fabric.api import *
from datetime import datetime, timedelta
import os,time
import commands
import random
import string
import pwd
import smtplib
import email
import email.mime.text
#from validate_email import validate_email
env.user='username'; # <- Remove this line if passwordless authentication enabled
env.password='password';# <- Remove this line if passwordless authentication enabled
def adduser(adduser,recipient):

sender_mail = 'temp_user_creation@domain.tld' #<- From address

three_hours_from_now=datetime.now() + timedelta(hours=3);#<- Replace this variable with number of hours you want the user to be available on the host.
user=adduser.split('@')[0];
recipients=['mailbox@domain.tld'] #<- Replace with your email address
recipients.append(recipient);
print "Creating user "+user+""
password = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(8))
print password
run("useradd -d /home/"+user+ " -s /bin/bash -p $( echo "+password+ "| openssl passwd -1 -stdin) " +user )
print "++++++++ Your Access credentials ++++++++"
print "Username:" +user
print "Password:" +password
print "++++++++++++++++++++++++++++++++++++++++++"
print "IMPORTANT: The user will be Automatically deleted after 3 Hours. Don't Store any Data on this Home directory"
print "Creating the required directories on the remote hosts"
cron_hour=str(format(three_hours_from_now, '%H'));
cron_minute=str(format(three_hours_from_now, '%M'));
find_user_cron='/opt/scripts/delete_user_'+user+'.py'
add_cron="echo \"" +cron_minute+ " " +cron_hour+ " * * * root " + "/usr/bin/python "+find_user_cron +" " +user +"\">>/etc/cron.d/user_remove"

run(add_cron);
#Section for delete_user_$user.py
delete_user_file ="#!/usr/bin/python\n"
delete_user_file += "import sys,os,subprocess\n"
delete_user_file += "import __main__ as main\n"
delete_user_file += "from datetime import datetime, timedelta\n"
print "Finding the cron running time.\n"
delete_user_file += "current_time=datetime.now();\n"
delete_user_file += "cron_hour=str(format(current_time,'%H'))\n"
delete_user_file += "cron_minute=str(format(current_time,'%M'))\n"
delete_user_file += "file=str((main.__file__)).strip('/opt/scripts/delete_user_')\n"
delete_user_file += "user=file.split('.')[0]\n"
#delete_user_file += "print delete_user_file;\n"
sed_command="sed -i \\\"/\"+user+ \"/d\\\" /etc/cron.d/user_remove"
delete_user_file += "os.system(\""+sed_command+"\")\n"
delete_user_file += "print \"Deleting the user\"\n"
delete_user_file += "deluser=sys.argv[1];\n"
delete_user_file += "print sys.argv[1];\n"
delete_user_file += "os.system(\"userdel -fr \" +deluser);\n"
tmp_script_file=open('/tmp/delete_user_'+user+'.py','w');
tmp_script_file.write(delete_user_file);
tmp_script_file.close();
run('mkdir -p /opt/scripts/')
putfile='/tmp/delete_user_'+user+'.py';
#print putfile;
put(putfile,'/opt/scripts/');
#Reloading Cron
run('/etc/init.d/crond reload');
table = "<table style='border: solid #ccc 1px ; border-collapse: collapse; box-shadow: 0 1px 1px #ccc;'><tr>"
th = "<th style='border: solid #ccc 1px; border-collapse: collapse; padding: 10px; text-align: left; background-color: #c1c1c1;"
th += "border-left: 1px solid #ccc; border-top: 1px solid #ccc;'>"
td = "<td style='border: solid #ccc 1px; border-collapse: collapse; padding: 10px; text-align: left;'>"

table_rd = "<table style='border: solid #FF0000 1px ; border-collapse: collapse; box-shadow: 0 1px 1px #FF0000;'><tr>"
th_rd = "<th style='border: solid #FF0000 1px; border-collapse: collapse; padding: 10px; text-align: left; background-color: #FF0000;"
th_rd += "border-left: 1px solid #FF0000; border-top: 1px solid #FF0000;'>"
td_rd = "<td style='border: solid #FF0000 1px; border-collapse: collapse; padding: 10px; text-align: left;'>"
body = "<html><head>"
body += "</head><body>\n"
body +="Hello <br />"
body +="The following user has been created on the host %s" %(env.host_string)
body += table_rd +"<tr>"
body += th_rd + "Hostname </th>"
body +=th_rd + "Username </th>"
body +=th_rd + "Creation Time </th>"
body +=th_rd + "Deletion Time </th></tr>"
body +="<tr>" + td_rd + env.host_string + "</td>"
body += td_rd + user + "</td>"
body += td_rd + str(datetime.now()) + "</td>"
body += td_rd + str(three_hours_from_now) + "</td>"
body += "</table>"

body_of_the_message = email.mime.text.MIMEText(body,'html');
message = email.MIMEMultipart.MIMEMultipart('alternative')
message['Subject'] ="User Creation Audit Report"
message['From'] = sender_mail
message['To'] =", ".join(recipients)
message.attach(body_of_the_message);
server = smtplib.SMTP('172.16.1.124')
server.sendmail(message['From'],recipients,message.as_string())
server.quit()
os.system("rm -f " +putfile);

Usage:

fab -H IPaddress adduser:dhanasekaran,recipient=user@domain.tld

Conclusion:

This automation provides a secure and efficient method for granting temporary access to production servers while minimising administrative overhead. By automatically removing user accounts after a specified duration, it helps enforce security policies, reduce the risk of unauthorized access, and eliminate the need for manual cleanup activities.

FAQs

1. What is the purpose of creating a temporary user?

A temporary user provides limited-time access to a server for tasks such as troubleshooting issues, checking logs, or performing maintenance. The account is automatically removed after the configured period.

2. How long will the temporary user remain active?

In this example, the user account remains active for 3 hours. The duration can be modified using the timedelta value in the script.

3. Can I change the temporary access duration?

Yes. You can change:

three_hours_from_now = datetime.now() + timedelta(hours=3)

For example, to allow access for 1 hour:

datetime.now() + timedelta(hours=1)
4. How is the temporary user’s password generated?

The script generates a random 8-character password using uppercase letters and numbers.

5. How are the temporary user credentials provided?

The script displays the generated username and password and also sends an email notification containing information about the user, host, creation time, and scheduled deletion time.

6. How is the user automatically deleted?

A temporary Python script is created on the remote server and scheduled through /etc/cron.d/user_remove. After the configured time, the cron job executes the script, which removes the user account.

7. What happens to the user’s home directory when the account is deleted?

The script uses:

userdel -fr username

The -r option removes the user’s home directory and associated files, while -f forces the deletion. Therefore, any data stored under the temporary user’s home directory will be removed.

Related Article:

How to Lock and Unlock a User on Ubuntu 24.04? – Pheonix Solutions

How do I create a read-only user on an Ubuntu server? – Pheonix Solutions

Talk to our experts

Have a technology challenge or looking for the right solution for your business? Our team can help you with cloud, DevOps, development, infrastructure, design, and more. Feel free to reach out to our experts here.

admin

Writes about Web & Architecture at Pheonix Solutions.

Leave a Reply

Scroll to Top