{"id":724,"date":"2016-07-12T07:50:55","date_gmt":"2016-07-12T02:20:55","guid":{"rendered":"https:\/\/pheonixsolutions.com\/blog\/?p=724"},"modified":"2026-09-10T14:10:45","modified_gmt":"2026-09-10T08:40:45","slug":"create-temporary-user-on-linux-host","status":"publish","type":"post","link":"https:\/\/pheonixsolutions.com\/blog\/create-temporary-user-on-linux-host\/","title":{"rendered":"Create temporary User on Linux Host"},"content":{"rendered":"\n<h3 class=\"wp-block-heading\"><strong>Introduction<\/strong><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Prerequisites<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Centralized box which has access to all production servers.<\/li>\n\n\n\n<li>All the requested python module installed.<\/li>\n\n\n\n<li>User needs to be deleted after 3 hours<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">Implementation:<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Passing username and hosts as variables while executing the script.<\/li>\n\n\n\n<li>Create Temporary user on the host with random password<\/li>\n\n\n\n<li>Send Notifications to recipient email address about user creation.<\/li>\n\n\n\n<li>Create a temporary file on the remote host to delete the user from the host.<\/li>\n\n\n\n<li>Add the temporary file to cron to delete the user after 3 hours(in our case)<\/li>\n\n\n\n<li>Delete the cron entry and user after 3 hours<\/li>\n<\/ol>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">#!\/usr\/bin\/env python\n#########Fab file to Create Temporary User########\n#Author:Dhanasekaran N\n#Email:support@pheonixsolutions.com\n#Version:0.1\n##################################################\nfrom fabric.api import env, run\nfrom fabric.api import *\nfrom datetime import datetime, timedelta\nimport os,time\nimport commands\nimport random\nimport string\nimport pwd\nimport smtplib\nimport email\nimport email.mime.text\n#from validate_email import validate_email\nenv.user='username'; # &lt;- Remove this line if passwordless authentication enabled\nenv.password='password';# &lt;- Remove this line if passwordless authentication enabled\ndef adduser(adduser,recipient):\n\nsender_mail = 'temp_user_creation@domain.tld'\u00c2\u00a0#&lt;- From address\n\nthree_hours_from_now=datetime.now() + timedelta(hours=3);#&lt;- Replace this variable with number of hours you want the user to be available on the host.\nuser=adduser.split('@')[0];\nrecipients=['mailbox@domain.tld']\u00c2\u00a0#&lt;- Replace with your email address\nrecipients.append(recipient);\nprint \"Creating user \"+user+\"\"\npassword = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(8))\nprint password\nrun(\"useradd -d \/home\/\"+user+ \" -s \/bin\/bash -p $( echo \"+password+ \"| openssl passwd -1 -stdin) \" +user )\nprint \"++++++++ Your Access credentials ++++++++\"\nprint \"Username:\" +user\nprint \"Password:\" +password\nprint \"++++++++++++++++++++++++++++++++++++++++++\"\nprint \"IMPORTANT: The user will be Automatically deleted after 3 Hours. Don't Store any Data on this Home directory\"\nprint \"Creating the required directories on the remote hosts\"\ncron_hour=str(format(three_hours_from_now, '%H'));\ncron_minute=str(format(three_hours_from_now, '%M'));\nfind_user_cron='\/opt\/scripts\/delete_user_'+user+'.py'\nadd_cron=\"echo \\\"\" +cron_minute+ \" \" +cron_hour+ \" * * * root \" + \"\/usr\/bin\/python \"+find_user_cron +\" \" +user +\"\\\">>\/etc\/cron.d\/user_remove\"\n\nrun(add_cron);\n#Section for delete_user_$user.py\ndelete_user_file =\"#!\/usr\/bin\/python\\n\"\ndelete_user_file += \"import sys,os,subprocess\\n\"\ndelete_user_file += \"import __main__ as main\\n\"\ndelete_user_file += \"from datetime import datetime, timedelta\\n\"\nprint \"Finding the cron running time.\\n\"\ndelete_user_file += \"current_time=datetime.now();\\n\"\ndelete_user_file += \"cron_hour=str(format(current_time,'%H'))\\n\"\ndelete_user_file += \"cron_minute=str(format(current_time,'%M'))\\n\"\ndelete_user_file += \"file=str((main.__file__)).strip('\/opt\/scripts\/delete_user_')\\n\"\ndelete_user_file += \"user=file.split('.')[0]\\n\"\n#delete_user_file += \"print delete_user_file;\\n\"\nsed_command=\"sed -i \\\\\\\"\/\\\"+user+ \\\"\/d\\\\\\\" \/etc\/cron.d\/user_remove\"\ndelete_user_file += \"os.system(\\\"\"+sed_command+\"\\\")\\n\"\ndelete_user_file += \"print \\\"Deleting the user\\\"\\n\"\ndelete_user_file += \"deluser=sys.argv[1];\\n\"\ndelete_user_file += \"print sys.argv[1];\\n\"\ndelete_user_file += \"os.system(\\\"userdel -fr \\\" +deluser);\\n\"\ntmp_script_file=open('\/tmp\/delete_user_'+user+'.py','w');\ntmp_script_file.write(delete_user_file);\ntmp_script_file.close();\nrun('mkdir -p \/opt\/scripts\/')\nputfile='\/tmp\/delete_user_'+user+'.py';\n#print putfile;\nput(putfile,'\/opt\/scripts\/');\n#Reloading Cron\nrun('\/etc\/init.d\/crond reload');\ntable = \"&lt;table style='border: solid #ccc 1px ; border-collapse: collapse; box-shadow: 0 1px 1px #ccc;'>&lt;tr>\"\nth = \"&lt;th style='border: solid #ccc 1px; border-collapse: collapse; padding: 10px; text-align: left; background-color: #c1c1c1;\"\nth += \"border-left: 1px solid #ccc; border-top: 1px solid #ccc;'>\"\ntd = \"&lt;td style='border: solid #ccc 1px; border-collapse: collapse; padding: 10px; text-align: left;'>\"\n\ntable_rd = \"&lt;table style='border: solid #FF0000 1px ; border-collapse: collapse; box-shadow: 0 1px 1px #FF0000;'>&lt;tr>\"\nth_rd = \"&lt;th style='border: solid #FF0000 1px; border-collapse: collapse; padding: 10px; text-align: left; background-color: #FF0000;\"\nth_rd += \"border-left: 1px solid #FF0000; border-top: 1px solid #FF0000;'>\"\ntd_rd = \"&lt;td style='border: solid #FF0000 1px; border-collapse: collapse; padding: 10px; text-align: left;'>\"\nbody = \"&lt;html>&lt;head>\"\nbody += \"&lt;\/head>&lt;body>\\n\"\nbody +=\"Hello &lt;br \/>\"\nbody +=\"The following user has been created on the host %s\" %(env.host_string)\nbody += table_rd +\"&lt;tr>\"\nbody += th_rd + \"Hostname &lt;\/th>\"\nbody +=th_rd + \"Username &lt;\/th>\"\nbody +=th_rd + \"Creation Time &lt;\/th>\"\nbody +=th_rd + \"Deletion Time &lt;\/th>&lt;\/tr>\"\nbody +=\"&lt;tr>\" + td_rd + env.host_string + \"&lt;\/td>\"\nbody += td_rd + user + \"&lt;\/td>\"\nbody += td_rd + str(datetime.now()) + \"&lt;\/td>\"\nbody += td_rd + str(three_hours_from_now) + \"&lt;\/td>\"\nbody += \"&lt;\/table>\"\n\nbody_of_the_message = email.mime.text.MIMEText(body,'html');\nmessage = email.MIMEMultipart.MIMEMultipart('alternative')\nmessage['Subject'] =\"User Creation Audit Report\"\nmessage['From'] = sender_mail\nmessage['To'] =\", \".join(recipients)\nmessage.attach(body_of_the_message);\nserver = smtplib.SMTP('172.16.1.124')\nserver.sendmail(message['From'],recipients,message.as_string())\nserver.quit()\nos.system(\"rm -f \" +putfile);<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Usage:<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><em>fab -H IPaddress&nbsp;adduser:dhanasekaran,recipient=user@domain.tld<\/em><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Conclusion:<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">FAQs<\/h2>\n\n\n\n<h5 class=\"wp-block-heading\">1. What is the purpose of creating a temporary user?<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h5 class=\"wp-block-heading\">2. How long will the temporary user remain active?<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">In this example, the user account remains active for <strong>3 hours<\/strong>. The duration can be modified using the <code>timedelta<\/code> value in the script.<\/p>\n\n\n\n<h5 class=\"wp-block-heading\">3. Can I change the temporary access duration?<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">Yes. You can change:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">three_hours_from_now = datetime.now() + timedelta(hours=3)<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">For example, to allow access for 1 hour:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">datetime.now() + timedelta(hours=1)<\/pre>\n\n\n\n<h5 class=\"wp-block-heading\">4. How is the temporary user&#8217;s password generated?<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">The script generates a random 8-character password using uppercase letters and numbers.<\/p>\n\n\n\n<h5 class=\"wp-block-heading\">5. How are the temporary user credentials provided?<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h5 class=\"wp-block-heading\">6. How is the user automatically deleted?<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">A temporary Python script is created on the remote server and scheduled through <code>\/etc\/cron.d\/user_remove<\/code>. After the configured time, the cron job executes the script, which removes the user account.<\/p>\n\n\n\n<h5 class=\"wp-block-heading\">7. What happens to the user&#8217;s home directory when the account is deleted?<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">The script uses:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">userdel -fr username<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>-r<\/code> option removes the user&#8217;s home directory and associated files, while <code>-f<\/code> forces the deletion. Therefore, any data stored under the temporary user&#8217;s home directory will be removed.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Related Article:<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><a href=\"https:\/\/pheonixsolutions.com\/blog\/how-to-lock-and-unlock-a-user-on-ubuntu-24-04\/\">How to Lock and Unlock a User on Ubuntu 24.04? &#8211; Pheonix Solutions<\/a><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><a href=\"https:\/\/pheonixsolutions.com\/blog\/how-do-i-create-a-read-only-user-on-an-ubuntu-server\/\">How do I create a read-only user on an Ubuntu server? &#8211; Pheonix Solutions<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Talk to our experts<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Have a technology challenge or looking for the right solution for your business? Our team can help you with <strong>cloud, DevOps, development, infrastructure, design, and more<\/strong>. Feel free to reach out to our experts <a href=\"https:\/\/pheonixsolutions.com\/contact\">here<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Introduction The following script will help you to create a temporary user on the host and delete all the content [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","ast-disable-related-posts":"","theme-transparent-header-meta":"","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"default","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":false,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"font":"","enabled":false},"version":2},"jetpack_post_was_ever_published":false},"categories":[1022],"tags":[],"class_list":["post-724","post","type-post","status-publish","format-standard","hentry","category-web-architecture","psol-cat-web-architecture"],"jetpack_publicize_connections":[],"jetpack_shortlink":"https:\/\/wp.me\/phn2x7-bG","jetpack_sharing_enabled":true,"jetpack_featured_media_url":"","_links":{"self":[{"href":"https:\/\/pheonixsolutions.com\/blog\/wp-json\/wp\/v2\/posts\/724","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/pheonixsolutions.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/pheonixsolutions.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/pheonixsolutions.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/pheonixsolutions.com\/blog\/wp-json\/wp\/v2\/comments?post=724"}],"version-history":[{"count":4,"href":"https:\/\/pheonixsolutions.com\/blog\/wp-json\/wp\/v2\/posts\/724\/revisions"}],"predecessor-version":[{"id":11631,"href":"https:\/\/pheonixsolutions.com\/blog\/wp-json\/wp\/v2\/posts\/724\/revisions\/11631"}],"wp:attachment":[{"href":"https:\/\/pheonixsolutions.com\/blog\/wp-json\/wp\/v2\/media?parent=724"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/pheonixsolutions.com\/blog\/wp-json\/wp\/v2\/categories?post=724"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/pheonixsolutions.com\/blog\/wp-json\/wp\/v2\/tags?post=724"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}