BASH
An error handling and logging template
#!/usr/bin/env bash
# This file:
#
# - errorhandle.sh
#
# Usage:
#
# source errorhandle.sh
#
# Based on a template by BASH3 Boilerplate v2.2.0
# http://bash3boilerplate.sh/#authors
#
# Exit on error. Append "|| true" if you expect an error.
set -o errexit
# Exit on error inside any functions or subshells.
set -o errtrace
# Do not allow use of undefined vars. Use ${VAR:-} to use an undefined VAR
set -o nounset
# Catch the error in pipe fail
set -o pipefail
# Turn on traces, useful while debugging but commented out by default
# set -o xtrace
# ---------------------------------------------------------------------------
# logging
PROGNAME=${0##*/}
VERSION="0.1"
echo >> /var/log/"$PROGNAME".log
exec 3>&1 4>&2
trap 'exec 2>&4 1>&3' 0 1 2 3
exec 1>>/var/log/"$PROGNAME".log 2>&1
echo $(TZ=":America/Los_Angeles" date) >> /var/log/"$PROGNAME".log
clean_up() { # Perform pre-exit housekeeping
return
}
error_exit() {
echo -e "${PROGNAME}: ${1:-"Unknown Error"}" >&2
clean_up
exit 1
}
graceful_exit() {
clean_up
exit
}
# Trap signals
trap "signal_exit TERM" TERM HUP
trap "signal_exit INT" INT
# Check for root UID
if [[ $(id -u) != 0 ]]; then
error_exit "You must be the superuser to run this script."
fi
Create user in samba active directory
/usr/local/samba/bin/samba-tool user create $userName $passWord \
--surname="$lastName" --given-name="$firstName" \
--mail-address="$email" \
--company="Company" \
--userou="OU=Primary Users,OU=$orgUnit" \
--profile-path=\\\\directory.ad.company.com\\profiles\\%USERNAME% \
--job-title="$jobTitle" \
--department="$department" \
--telephone-number="123-456-8800" \
--physical-delivery-office="$orgUnit"
Create automated OpenVPN certificate
expect <<END
spawn ./build-key-pass --batch $certificatename
expect "*?phrase:"
send "$password\r"
expect "*?phrase:"
send "$password\r"
expect eof
END
Python
Find ldap (active directory) membership
#!/usr/bin/env python
import ldap,ldif, sys
thefile = open('maillistmembers.txt', 'w')
server = 'ldaps://ad.company.com/'
con = ldap.initialize(server)
bind_dn="[email protected]"
bind_pw="verylongpasswordhere"
base_dn="OU=Mail Lists,dc=ad,dc=company,dc=com"
con.simple_bind_s(bind_dn, bind_pw )
searchScope = ldap.SCOPE_SUBTREE
results = con.search_s(base_dn, ldap.SCOPE_SUBTREE)
#print (len(results))
for item in results:
print (item[1].get('name'))
thefile.write("%s\n" % item[1].get('name')[0])
thefile.write("\n\n")
#print(results[0][1].get('member')) # memberlist
#print(results[0][1].get('name')) # maillist name
for grandlistitem in results:
listname=grandlistitem[1].get('name')[0]
thefile.write("%s\n" % listname)
thefile.write("%s" % '--' * 50)
thefile.write(" \n")
if (grandlistitem[1].get('name')=='Mail Lists'):
break
else:
for memberl in grandlistitem[1].get('member'):
actualmember=memberl.split(',')[0].split('=')[1]
#memberlist.append(actualmember)
thefile.write("%s\n" % actualmember)
thefile.write(" \n\n")
TODO application with the ability to add, view and delete todo items
#!/usr/bin/env python3
from collections import Counter
def initial():
print('Welcome to todo application')
print('Your todo list is currently empty')
def add_todo(todo_arr):
" add todo items "
while True:
priority = input('Please enter integer priority (integer or done)\n')
if priority == 'done':
break
while True:
try:
priority = int(priority)
todo = input('Your todo item, to quit adding, say done\n')
break
except:
print('priority must be integer')
todo_arr.append([priority, todo])
return todo_arr
def display(todo_arr):
"display todo array"
if todo_arr:
# priority frequency calculate
freq_counter = Counter([l[0] for l in todo_arr])
# find missing priorities
missing_priorities = []
priorities = freq_counter.keys()
priorities = sorted(list(set(priorities)))
min_prio = min(priorities)
max_prio = max(priorities)
print('debug', priorities, max_prio, min_prio)
if min_prio < max_prio:
for item in range(max_prio):
if item not in priorities:
missing_priorities.append(item)
for item in todo_arr:
print('[', item[0], ' ]', freq_counter[item[0]], item[1])
if missing_priorities:
print('these priorities are missing', missing_priorities)
def delete_todo(todo_arr):
"delete todo items"
while todo_arr:
del_idxs = input('Enter the indexes of items to delete,eg 12 or done\n')
if del_idxs == 'done':
break
print('you entered', del_idxs)
del_idx_int = [ int(i) for i in list(del_idxs) ]
# delete highest index first
del_idx_int = sorted(del_idx_int, reverse=True)
# check the max range
if del_idx_int[0] > len(todo_arr) -1:
print('one of the index is higher than maximum elements')
break
for item in del_idx_int:
del todo_arr[item]
# [4] Item
def show_menu(todo_arr):
pr = """
(A)dd
(D)elete
(V)iew
(Q)uit
Enter choice: """
while True:
while True:
try:
choice = input(pr).strip()[0].lower()
except(EOFError, KeyboardInterrupt, IndexError):
choice = 'q'
print('\n Your choice:', choice)
if choice not in 'advq':
print('Invalid option, try again')
else:
break
if choice == 'q':
break
if choice == 'a':
todo_arr = add_todo(todo_arr)
if choice == 'd':
delete_todo(todo_arr)
if choice == 'v':
display(todo_arr)
# Welcome message
initial()
# Empty todo array
todo_arr = []
show_menu(todo_arr)
# Quit todo?
print('Goodbye!')