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.

Assumption:

  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

Work Flow:

  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

 

Leave a Reply