Browse Source

Merge pull request #6 from butlerx/cleanup

clean up code for testing
master
Cian Butler 4 years ago
committed by GitHub
parent
commit
a2ec0d2f4b
38 changed files with 519 additions and 999 deletions
  1. +28
    -0
      .codeclimate.yml
  2. +13
    -25
      accounts.d/clubsocs_accounts_disable.sh
  3. +0
    -3
      accounts.d/get_all_student_members.sh
  4. +5
    -7
      accounts.d/how_many_newbies_logged_in.sh
  5. +0
    -22
      accounts.d/mailtosocs.txt
  6. +9
    -9
      bash/add_hg_repo.sh
  7. +54
    -0
      bash/check_fix_gids.sh
  8. +14
    -0
      bash/check_if_emails_in_ldap.sh
  9. +2
    -2
      bash/daily-permissions-check
  10. +12
    -12
      bash/mv_quota.sh
  11. +22
    -0
      bash/mysql-slave-permissions.sh
  12. +36
    -0
      bash/postgres_add
  13. +92
    -0
      bash/rbsearch
  14. +6
    -6
      bash/report_rbpkg
  15. +0
    -61
      check_fix_gids.sh
  16. +0
    -14
      check_if_emails_in_ldap.sh
  17. +3
    -3
      disusered.bash
  18. +0
    -18
      fix_web_logs
  19. +0
    -94
      groupmail.py
  20. +35
    -37
      ldap/ldapmodify_ldif.py
  21. +0
    -2
      ldap/ldapsearch.txt
  22. +0
    -10
      ldap/ldif_founder_soc_fix.py
  23. +8
    -8
      ldap/newyear_ldif.py
  24. +0
    -8
      legacy/VM/create_vm
  25. +0
    -243
      legacy/VM/xen_deffault.conf
  26. +0
    -104
      legacy/faststorage_add.pl
  27. +0
    -80
      legacy/pcp
  28. +0
    -21
      legacy/twitter_rss.sh
  29. +0
    -11
      legacy/update_pkgsrc.sh
  30. +0
    -30
      mysql-slave-permissions.sh
  31. +0
    -37
      not_a_user_db.py
  32. +0
    -0
      perl/mysql_add
  33. +0
    -2
      postgres_add
  34. +118
    -0
      python/groupmail.py
  35. +33
    -0
      python/not_a_user_db.py
  36. +29
    -0
      python/yearspaid_mak_fix.py
  37. +0
    -99
      rbsearch
  38. +0
    -31
      yearspaid_mak_fix.py

+ 28
- 0
.codeclimate.yml View File

@@ -0,0 +1,28 @@
engines:
duplication:
enabled: true
config:
languages:
- bash
- python
- perl
fixme:
enabled: true
pep8:
enabled: true
checks:
E501:
enabled: false
E302:
enabled: false
radon:
enabled: true
checks:
Complexity:
enabled: false
shellcheck:
enabled: true
ratings:
paths:
- "**"
exclude_paths: []

+ 13
- 25
accounts.d/clubsocs_accounts_disable.sh View File

@@ -9,38 +9,26 @@ dcu=$(ldapsearch -xLLL "(gidnumber=31382)" | grep dn | awk -F = '{print $2}' | a
projects=$(ldapsearch -xLLL "(gidnumber=1014)" | grep dn | awk -F = '{print $2}' | awk -F , '{print $1}')
intersocs=$(ldapsearch -xLLL "(gidnumber=1016)" | grep dn | awk -F = '{print $2}' | awk -F , '{print $1}')

list=$(echo "$clubs\n$socs\n$dcu\n$projects\n$intersocs")
list="$clubs\n$socs\n$dcu\n$projects\n$intersocs"

msg=/srv/admin/scripts/accounts.d/message.txt

#for user in $(ls /home/society)
echo "You are about to disable all Impersonal RedBrick Accounts - To proceed type \"Proceed\", Print will show the accounts about to be diabled"
read ans
read -r ans

if [ "$ans" = "Proceed" ]; then
for user in $list
do
useradm resetpw -M $user
useradm setshell $user /usr/local/shells/disabled ]
altmail=$(useradm show $user | grep altmail | awk '{print $2}')
cat $msg | mutt -s "Your RedBrick Account" $user $altmail
done

for user in $list; do
useradm resetpw -M "$user"
useradm setshell "$user" /usr/local/shells/disabled
altmail=$(useradm show "$user" | grep altmail | awk '{print $2}')
mutt -s "Your RedBrick Account" "$user" "$altmail" < $msg
done
elif [ "$ans" = "Print" ]; then
for i in $list
do
echo $i
done

for i in $list; do
echo "$i"
done
else
echo Exiting
exit
echo Exiting
exit
fi

#for user in `ls /home/club`
#do
# useradm resetpw -M $user
# useradm setshell $user /usr/local/shells/disabled
# altmail=$(useradm show $user | grep altmail | awk '{print $2}')
# cat $msg | mutt -s "Your Club RedBrick Account" $user $altmail
#done

+ 0
- 3
accounts.d/get_all_student_members.sh View File

@@ -1,3 +0,0 @@
useradm=/srv/admin/scripts/rrs/useradm

for a in `useradm`

+ 5
- 7
accounts.d/how_many_newbies_logged_in.sh View File

@@ -1,12 +1,10 @@
#!/bin/bash
NUMBER=0

for a in $(/srv/admin/scripts/rrs/useradm list_newbies)
do
finger $a | grep "Last login"

if [ $? -eq 0 ]; then
NUMBER=$[$NUMBER+1]
fi
for a in $(/srv/admin/scripts/rrs/useradm list_newbies); do
if finger "$a" | grep "Last login"; then
NUMBER=$(("$NUMBER"+1))
fi
done

echo $NUMBER

+ 0
- 22
accounts.d/mailtosocs.txt View File

@@ -1,22 +0,0 @@
Hello folks,

I'd firstly like to apologise on behalf of the redbrick admins,
We had a script that mailed all of the clubs and socs about
membership renewals when it shouldn't have.

I would like to just reconfirm that all clubs and socs do have free web
hosting with redbrick and your membership will automatically be renewed
each year.

Assuming you reading this are the webmaster for your society,
would you be interested in a tutorial that goes through the various
elements to redbricks webhosting? OR would you instead be interested
in an online resource or page that just has all the (clubs & socs)
hosting information you need?

I'd be grateful if you could get back to me on mak@redbrick.dcu.ie
with some feedback on the questions above,

Kind regards,

maK - redbrick Admin

add_hg_repo.sh → bash/add_hg_repo.sh View File

@@ -11,13 +11,13 @@ WEBHOST=morpheus
ALLOW_ARCHIVE="gz zip bz2"
CHOWN=/bin/chown

if [[ $HOSTNAME != $WEBHOST ]]; then
if [[ $HOSTNAME != "$WEBHOST" ]]; then
echo "This script must be run on the web server ($WEBHOST)."
exit 1
fi

echo "What will this repository be called?"
read REPONAME
read -r REPONAME

if [[ -e $COLLECTION/$REPONAME ]]; then
echo "This repository already exists! Aborting."
@@ -25,13 +25,13 @@ if [[ -e $COLLECTION/$REPONAME ]]; then
fi

echo "What users should have write access to $REPONAME? (space separated list)"
read USERLIST
read -r USERLIST

echo "Enter a brief description of this repository:"
read DESCRIPTION
read -r DESCRIPTION

echo "Enter a primary contact in the form Name <emailaddress@host.com>:"
read CONTACT
read -r CONTACT

echo "Please confirm that the following details are correct:"
echo "Repository name: $REPONAME"
@@ -44,7 +44,7 @@ ANSWER=""

while [[ $ANSWER != "y" ]] && [[ $ANSWER != "n" ]]; do
echo -n "(y/n) "
read ANSWER
read -r ANSWER
done

if [[ $ANSWER == "n" ]]; then
@@ -53,9 +53,9 @@ if [[ $ANSWER == "n" ]]; then
fi

echo "Init repository..."
$HG init $COLLECTION/$REPONAME
$HG init $COLLECTION/"$REPONAME"
echo "Create configuration file..."
cat > $COLLECTION/$REPONAME/.hg/hgrc << EOF
cat > $COLLECTION/"$REPONAME"/.hg/hgrc << EOF
[web]
allow_push = $USERLIST
contact = $CONTACT
@@ -63,7 +63,7 @@ description = $DESCRIPTION
allow_archive = $ALLOW_ARCHIVE
EOF
echo "Fix permissions..."
$CHOWN -R $APACHE_UID:$APACHE_GID $COLLECTION/$REPONAME
$CHOWN -R $APACHE_UID:$APACHE_GID $COLLECTION/"$REPONAME"
echo "Operation complete"

exit 0

+ 54
- 0
bash/check_fix_gids.sh View File

@@ -0,0 +1,54 @@
#!/bin/bash

#Get Gids from LDAP
names=$(ldapsearch -xLLL "(objectClass=posixGroup)" gidNumber | grep dn | awk -F = '{print $2}' | awk -F , '{print $1}')
ids=$(ldapsearch -xLLL "(objectClass=posixGroup)" gidNumber | grep gidNumber | awk '{print $2}')
count=$(ldapsearch -xLLL "(objectClass=posixGroup)" gidNumber | grep -c dn)

#Convet strings to Arrays
acount=$(("$count" - 1))

for i in $(seq 1 "$count"); do
# echo loop debug $i
ai=$(("$i" - 1))
a_names[$ai]=$(echo "$names" | awk '{print $'"$i"'}')
# echo ${a_names[$ai]}
a_ids[$ai]=$(echo "$ids" | awk '{print $'"$i"'}')
# echo ${a_ids[$ai]}
done

#Compare LDAP GIDS to System GIDS

for a in $(seq 0 $acount); do
# echo ${a_names[$a]}
# Check for group name in /etc/groups
if [ "$(grep -c "${a_names[$a]}" /etc/group)" -gt 0 ]; then
# Check its been assigned the right gid
[ "$(grep "${a_names[$a]}" /etc/group | awk -F : '{print $3}')" = "${a_ids[$a]}" ] || echo FUCK UP IN "${a_names[$a]}" Group is not assigned the correct GID
else
#IF Group is not there WARN AND ASK TO FIX
echo "${a_names[$a]}:x:${a_ids[$a]} not in /etc/group"
# Check for GID in use
if [ "$(grep -c :"${a_ids[$a]}": /etc/group)" -gt 0 ]; then
#GID is in use
echo GID "${a_ids[$a]}" in use by "$(grep :"${a_ids[$a]}": /etc/group | awk -F : '{print $1}')"
#This is complicated bit that requires finding and chgrping files in use by GID
#genetate new gid
RANDOM=$a
newgid=$RANDOM
while [ "$(grep -c :"$newgid": /etc/group)" -gt 0 ]; do
newgid=$RANDOM
done
echo New GID is "$newgid"
else
echo GID "${a_ids[$a]}" not in use
# Append GID and name to /etc/group possible ask first
echo "${a_names[$a]}:x:${a_ids[$a]}:" >> /etc/group
#may use a fix variable for this instead and do writing at the end
fi
fi
done

#ASSIGN NEW GIDS

#CHECH AND FIX GIDS of FILES NOT IN /STORAGE OR /FAST-STORAGE or TMP Dirs

+ 14
- 0
bash/check_if_emails_in_ldap.sh View File

@@ -0,0 +1,14 @@
#! /bin/bash

# Input : a file with a list of email addresses (one address per line)
# Check if the email is in our ldap, if not return the email address.

echo "Enter path to list of emails"
read -r FILE
while read -r line
do
if [ -z "$(ldapsearch -D cn=root,ou=ldap,o=redbrick -xLLL -y /etc/ldap.secret "altmail=$line" uid)" ]
then
echo "$line"
fi
done <"$FILE"

daily-permissions-check → bash/daily-permissions-check View File

@@ -13,7 +13,7 @@ exit 0
echo
echo "-------------[ /root permissions ]------------------"
root_permission=$(stat /root | grep -c "Access: (0700/drwx------)")
if [ $root_permission -ne 1 ]
if [ "$root_permission" -ne 1 ]
then
echo "WARNING: The permissions on /root are NOT 0700"
else
@@ -33,7 +33,7 @@ find /root -type f -not -gid 0 -not -uid 0 -printf "%m \t %u:%g \t %P \n"
echo
echo "-------------[ ldap.secret permissions ]------------------"
root_permission=$(stat /etc/ldap.secret | grep -c "Access: (0400/-r--------)")
if [ $root_permission -ne 1 ]
if [ "$root_permission" -ne 1 ]
then
echo "WARNING: The permissions on /etc/ldap.secret are NOT 0400"
else

mv_quota.sh → bash/mv_quota.sh View File

@@ -12,40 +12,40 @@ new_flimit=2000000
#Get users start for loop
for user in $(getent passwd | awk -F : '{print $1}'); do
#Check for actual users with quotas
if [ $(quota -lu $user | grep -c $device) -eq "1" ]; then
old_bquota=$(quota -lu $user | grep $device | awk '{print $3}')
old_blimit=$(quota -lu $user | grep $device | awk '{print $4}')
old_fquota=$(quota -lu $user | grep $device | awk '{print $6}')
old_flimit=$(quota -lu $user | grep $device | awk '{print $7}')
if [ "$(quota -lu "$user" | grep -c $device)" -eq "1" ]; then
old_bquota=$(quota -lu "$user" | grep $device | awk '{print $3}')
old_blimit=$(quota -lu "$user" | grep $device | awk '{print $4}')
old_fquota=$(quota -lu "$user" | grep $device | awk '{print $6}')
old_flimit=$(quota -lu "$user" | grep $device | awk '{print $7}')
#Compare old v new and setup values for set quota:
#Block Quota
if [ $old_bquota -lt $new_bquota ]; then
if [ "$old_bquota" -lt $new_bquota ]; then
bquota=$new_bquota
else
bquota=$old_bquota
bquota=$old_bquota
fi
#Block Limit
if [ $old_blimit -lt $new_blimit ]; then
if [ "$old_blimit" -lt $new_blimit ]; then
blimit=$new_blimit
else
blimit=$old_blimit
fi
#File Quota
if [ $old_fquota -lt $new_fquota ]; then
if [ "$old_fquota" -lt $new_fquota ]; then
fquota=$new_fquota
else
fquota=$old_fquota
fi
#File Limit
if [ $old_flimit -lt $new_flimit ]; then
if [ "$old_flimit" -lt $new_flimit ]; then
flimit=$new_flimit
else
flimit=$old_flimit
fi
#Set the users Quota on New Device
setquota -u $user $bquota $blimit $fquota $flimit $ndevice
setquota -u "$user" "$bquota" "$blimit" "$fquota" "$flimit" "$ndevice"
#Testing:
echo User: $user
echo User: "$user"
echo -e "Old Quota: $device\t$old_bquota\t$old_blimit\t$old_fquota\t$old_flimit"
echo -e "New Quota: $ndevice\t$bquota\t$blimit\t$fquota\t$flimit"
else

+ 22
- 0
bash/mysql-slave-permissions.sh View File

@@ -0,0 +1,22 @@
#!/bin/bash

date=$(date +%Y%m%d)
success=0
loops=0

while [ $success -eq 0 ]; do
success=$(grep -c success /backup/mysql/"$date"/summary)
if [ "$success" -gt 0 ]; then
files=$(find /backup/mysql/"$date"/tree/dumps/ -type f -printf "%P \n")
for file in $files; do
username=${file%.sql}
group=$(id -g "$username")
chown "$username":"$group" /backup/mysql/"$date"/tree/dumps/"$file"
done
elif [ $loops -gt 12 ]; then
exit 1
else
$loops++
sleep 1800
fi
done

+ 36
- 0
bash/postgres_add View File

@@ -0,0 +1,36 @@
#!/bin/bash

SCRIPTNAME="postgres_add"
USERNAME="micro"

function usage () {
echo "Usage: $SCRIPTNAME [ -u | --username ] user"
echo "eg. $SCRIPTNAME -u $USERNAME"
echo " $SCRIPTNAME --username $USERNAME"
echo ""
}

if [[ $# -eq 0 ]]; then
echo "Enter the user to create the db for"
read -r USER
fi

while [[ $# -gt 1 ]]; do
key="$1"
case $key in
-u|--username)
USER="$2"
shift
;;
-h|--help)
usage
;;
*)
echo Unrecognised flag
usage
;;
esac
shift
done

su postgres -c "createuser --no-superuser --no-createdb --no-createrole $USER; createdb $USER -O $USER"

+ 92
- 0
bash/rbsearch View File

@@ -0,0 +1,92 @@
#!/bin/bash

# Quick ldap search tool
# ver 0.1 sonic - I will never ever update this
# ver 0.2 koffee - quick update & shell checking
# ver 0.3 butlerx - add support for dcu AD

SCRIPTNAME="rbsearch"
EMAIL="bill.gates@hotmail.com"
USERNAME="microbg"
FULLNAME="Bill Gates"

SEARCH="ldapsearch -D cn=root,ou=ldap,o=redbrick -xLLL -y /etc/ldap.secret"

function dcusearch () {
if [ ! -z "$2" ]; then
SEARCH="$1 $2"
else
SEARCH=$1
fi
ldapsearch -x -h ad.dcu.ie -D "CN=rblookup,OU=Service Accounts,DC=ad,DC=dcu,DC=ie" -w "$(</etc/ldap_dcu.secret)" -b "OU=Students,DC=ad,DC=dcu,DC=ie" -s sub "($SEARCH)" cn gecos mail
}

function usage () {
echo "Usage: $SCRIPTNAME [-altmail] [-uid] [-id] [-name] [-nick] [-fullname] [--dcu [username] [fullname]] query"
echo "eg. $SCRIPTNAME -altmail $EMAIL"
echo " $SCRIPTNAME -uid $USERNAME"
echo " $SCRIPTNAME -fullname $FULLNAME"
echo " $SCRIPTNAME -update $USERNAME"
echo " $SCRIPTNAME -dcu username $USERNAME"
echo " $SCRIPTNAME -dcu fullname $FULLNAME"
echo ""
echo "Only fullname takes 2 arguments."
echo "All results will give just uid(s) apart from [-uid]"
echo "[-uid] prints all ldap info for that uid"
}

case $1 in
-update)
if [ ! -z "$3" ]; then
$SEARCH "cn=*$2*$3" uid yearsPaid loginShell
else
echo "Usage: $SCRIPTNAME -fullname $FULLNAME"
fi
;;
-altmail)
$SEARCH "altmail=$2" uid
;;
-uid|--user|-u)
$SEARCH "uid=$2"
;;
-id)
$SEARCH "id=$2" uid
;;
-name)
$SEARCH "cn=*$2*" uid
;;
-nick)
$SEARCH "gecos=*$2*" uid
;;
-fullname)
if [ ! -z "$3" ]; then
$SEARCH "cn=*$2*$3" uid
else
echo "Usage: $SCRIPTNAME -fullname $FULLNAME"
fi
;;
-newbie)
$SEARCH "newbie=TRUE" uid
;;
--dcu)
case $2 in
username)
SEARCH="cn=$3"
dcusearch "$SEARCH"
;;
fullname)
if [ ! -z "$4" ]; then
SEARCH="displayName=$3 $4"
dcusearch "$SEARCH"
else
echo "Usage: $SCRIPTNAME -dcu fullname $FULLNAME"
fi
esac
;;
-h|--help)
usage
;;
*)
usage
;;
esac

report_rbpkg → bash/report_rbpkg View File

@@ -5,11 +5,11 @@ FILENAME="rbpkg-packages-report"
# Move what happened yeterday to old log

if [ -f /var/log/$FILENAME.log ]; then
mv /var/log/$FILENAME.log /var/log/$FILENAME.log.old
mv /var/log/$FILENAME.log /var/log/$FILENAME.log.old
fi

if [ -f /var/log/$FILENAME.daily ]; then
rm /var/log/$FILENAME.daily
rm /var/log/$FILENAME.daily
fi

# log packages here today
@@ -17,11 +17,11 @@ fi
find ~rbpkg/packages -type f -name "*.deb" > /var/log/$FILENAME.log

for package in $(cat /var/log/$FILENAME.log /var/log/$FILENAME.log.old /var/log/$FILENAME.log.old | sort | uniq -u) ; do
LINES=$(apt-listchanges -f text -a $package 2>/dev/null | grep -m1 -n " -- " | awk -F: '{print $1}')
apt-listchanges -f text -a $package 2> /dev/null | head -n$LINES >> /var/log/$FILENAME.daily
echo >> /var/log/$FILENAME.daily
LINES=$(apt-listchanges -f text -a "$package" 2>/dev/null | grep -m1 -n " -- " | awk -F: '{print $1}')
apt-listchanges -f text -a "$package" 2> /dev/null | head -n "$LINES" >> /var/log/$FILENAME.daily
echo >> /var/log/$FILENAME.daily
done

if [ -s /var/log/$FILENAME.daily ]; then
cat /var/log/$FILENAME.daily | mutt -s "RB Package Report" system-reports@redbrick.dcu.ie
mutt -s "RB Package Report" system-reports@redbrick.dcu.ie < /var/log/$FILENAME.daily
fi

+ 0
- 61
check_fix_gids.sh View File

@@ -1,61 +0,0 @@
#!/bin/bash

#Get Gids from LDAP

names=`ldapsearch -xLLL "(objectClass=posixGroup)" gidNumber | grep dn | awk -F = '{print $2}' | awk -F , '{print $1}'`

ids=`ldapsearch -xLLL "(objectClass=posixGroup)" gidNumber | grep gidNumber | awk '{print $2}'`

count=`ldapsearch -xLLL "(objectClass=posixGroup)" gidNumber | grep -c dn`

#Convet strings to Arrays

acount=`expr $count - 1`

for i in `seq 1 $count`; do
# echo loop debug $i
ai=`expr $i - 1`
a_names[$ai]=`echo $names | awk '{print $'$i'}'`
# echo ${a_names[$ai]}
a_ids[$ai]=`echo $ids | awk '{print $'$i'}'`
# echo ${a_ids[$ai]}

done

#Compare LDAP GIDS to System GIDS

for a in `seq 0 $acount`; do
# echo ${a_names[$a]}
# Check for group name in /etc/groups
# [ `grep -c ${a_names[$a]} /etc/group` -eq 1 ] && echo "${a_names[$a]} in /etc/group" || echo "${a_names[$a]} not in /etc/group"
if [ `grep -c ${a_names[$a]} /etc/group` -gt 0 ]; then
# Check its been assigned the right gid
[ `grep ${a_names[$a]} /etc/group | awk -F : '{print $3}'` = ${a_ids[$a]} ] || echo FUCK UP IN ${a_names[$a]} Group is not assigned the correct GID
else
#IF Group is not there WARN AND ASK TO FIX
echo "${a_names[$a]}:x:${a_ids[$a]} not in /etc/group"
# Check for GID in use
# [ `grep -c ${a_ids[$a]} /etc/group` -gt 0 ] && echo GID ${a_ids[$a]} in use || echo GID ${a_ids[$a]} not in use
if [ `grep -c :${a_ids[$a]}: /etc/group` -gt 0 ]; then
#GID is in use
echo GID ${a_ids[$a]} in use by `grep :${a_ids[$a]}: /etc/group | awk -F : '{print $1}'`
#This is complicated bit that requires finding and chgrping files in use by GID
#genetate new gid
RANDOM=$a
newgid=$RANDOM
while [ `grep -c :$newgid: /etc/group` -gt 0 ]; do
newgid=$RANDOM
done
echo New GID is $newgid
else
echo GID ${a_ids[$a]} not in use
# Append GID and name to /etc/group possible ask first
echo "${a_names[$a]}:x:${a_ids[$a]}:" >> /etc/group
#may use a fix variable for this instead and do writing at the end
fi
fi
done

#ASSIGN NEW GIDS

#CHECH AND FIX GIDS of FILES NOT IN /STORAGE OR /FAST-STORAGE or TMP Dirs

+ 0
- 14
check_if_emails_in_ldap.sh View File

@@ -1,14 +0,0 @@
#! /bin/bash

# Input : a file with a list of email addresses (one address per line)
# Check if the email is in our ldap, if not return the email address.

FILE=/home/aziz/emails.new

while read line
do
if [ -z "$(ldapsearch -D cn=root,ou=ldap,o=redbrick -xLLL -y /etc/ldap.secret "altmail=$line" uid)" ]
then
echo $line
fi
done <$FILE

+ 3
- 3
disusered.bash View File

@@ -1,15 +1,15 @@
#! /bin/sh
#Doesn't work with SIGINT, even though it should, fml :)

trap '' 1 2 3 18 22 23 24 30
trap '' 1 2 3 CHLD TTOU TSTP XCPU

echo "--------------------------------------------------------------------------------"
echo " Your account has been disabled "
echo "--------------------------------------------------------------------------------"
echo ""

if [ -f /storage/daft/$LOGNAME ] && [ -s /storage/daft/$LOGNAME ] && [ -r /storage/daft/$LOGNAME ]; then
cat /storage/daft/$LOGNAME
if [ -f /storage/daft/"$LOGNAME" ] && [ -s /storage/daft/"$LOGNAME" ] && [ -r /storage/daft/"$LOGNAME" ]; then
cat /storage/daft/"$LOGNAME"
fi

echo ""


+ 0
- 18
fix_web_logs View File

@@ -1,18 +0,0 @@
#!/bin/zsh

year=$(date +%Y)
month=$(date +%m)
DAY=$(date +%d)
logdir='/var/log/apache2/'

find $logdir$year/$month/ -type f | xargs chmod 644
find $logdir$year/ -type d | xargs chmod 755

if [ $DAY -ne 1 ]; then
yesterday=$((DAY-1))
if [ $yesterday -lt 10 ]; then
find $logdir$year/$month/ -name "0$yesterday*log" -type f | xargs -n1 bzip2
else
find $logdir$year/$month/ -name "$yesterday*log" -type f | xargs -n1 bzip2
fi
fi

+ 0
- 94
groupmail.py View File

@@ -1,94 +0,0 @@
#!/usr/bin/python

"""
-maK
This is a script to send a mail to a group
defined by an ldap search
or simply send a singular mail

use ./groupmail -h
"""
import smtplib, string, argparse, os

def sendmail(frm, to, subject, body, cc):
if(cc == None):
cc = ''
msg = string.join((
'From: %s' % frm,
'To: %s' % to,
'CC: %s' % cc,
'Subject: %s' % subject,
'',
'%s' % body), "\r\n")

try:
smtp = smtplib.SMTP('mail.redbrick.dcu.ie')
smtp.sendmail(frm, to, msg)
smtp.quit()
except:
print 'Error sending mail to ' + to

def mailgroup(ldif, frm, subject, body, cc, prnt):
tomail = string.split(ldif, 'dn: uid=')
cn = ''
altmail = ''
uid = ''
for u in range(1,len(tomail)):
credentials = string.split(tomail[u], '\n')
for i in credentials:
if(i.startswith('uid: ')):
uid = i.split()[1]
if(i.startswith('cn: ')):
cn = i.split('cn: ')[1]
if(i.startswith('altmail: ')):
altmail = i.split()[1]
if(prnt):
print uid + ' - ' + cn + ' : ' + altmail
else:
#Send mail to each
print 'Send mail to '+cn+' using '+altmail+' (y|n)?'
send = raw_input('default(y): ')
if((send == 'n') or (send == 'N')):
print 'Mail not sent to '+cn+' using '+altmail+'\n'
else:
sendmail(frm, altmail.strip(), subject, body, cc)
print 'Mail sent to '+cn+' using '+altmail+'\n'

def main():
parser = argparse.ArgumentParser(description='Used to mail an ldap group/groups')
parser.add_argument('-g',dest='GROUPS', type=str, help='Specify groups or singular group. (eg. club or club,society,founders,redbrick)')
parser.add_argument('-p',dest='PRINT', action='store_true', help='Only print details - Do not send')
parser.add_argument('-f',dest='FROM', type=str, help='Who the mail is from.')
parser.add_argument('-cc',dest='CC', type=str, help='cc all mails to.')
parser.add_argument('-m',dest='MSG', type=str, help='Location of Message to be sent (text file etc)')
parser.add_argument('-t',dest='TO', type=str, help='Who singular mail is To.')
parser.add_argument('-s',dest='SUBJECT', type=str, help='Subject of mail.')
a = parser.parse_args()

if a.GROUPS != None:
if ',' in a.GROUPS:
searchParams = string.split(a.GROUPS, ',')
else:
searchParams = a.GROUPS
ldapsearch = 'ldapsearch -D cn=root,ou=ldap,o=redbrick -y /etc/ldap.secret -xLLL '
if isinstance(searchParams, str):
ldapsearch += '"(objectClass='+searchParams+')" uid cn altmail'
else:
ldapsearch += '"(|'
for i in searchParams:
ldapsearch += '(objectClass='+ i +')'
ldapsearch += ')" uid cn altmail'

ldif = os.popen(ldapsearch).read()
mailgroup(ldif, '','','','',a.PRINT)
exit()

if a.MSG != None:
with open(a.MSG, 'r') as content:
a.MSG = content.read()

if a.GROUPS == None and a.FROM != None and a.TO != None and a.SUBJECT != None and a.MSG != None and a.PRINT == False:
sendmail(a.FROM, a.TO, a.SUBJECT, a.MSG, a.CC)

if __name__ == '__main__':
main()

+ 35
- 37
ldap/ldapmodify_ldif.py View File

@@ -1,6 +1,4 @@
#!/usr/bin/python
import sys,string

"""
-mak
This simply takes the ldif generated by newyear_ldif.py
@@ -9,41 +7,41 @@ and builds it into an ldapmodify formatted ldif.
To be used with the ldap modify query below
ldapmodify -x -D cn=root,ou=ldap,o=redbrick -y /etc/ldap.secret -f [LDIF_FROM_THIS_SCRIPT]
"""
import sys

yearsPaid = ''
uid = ''

#print modify ldif template
def modifyTemplate(uid,yearsPaid,newbie,reserved):
if uid != '' and yearsPaid != '' and reserved == False:
modTemp = "dn: uid="+uid.strip()+"\nchangetype: modify\nreplace: yearsPaid\nyearsPaid: "+yearsPaid.strip()+"\n"
if newbie == '1':
modTemp += "-\nreplace: newbie\nnewbie: FALSE\n\n"
else:
modTemp += "\n"
print modTemp
def modify_template(l_uid, l_years_paid, l_newbie, l_reserved):
"""print modify ldif template"""
if l_uid != '' and l_years_paid != '' and l_reserved is False:
mod_temp = "dn: uid=" + l_uid.strip() +\
"\nchangetype: modify\nreplace: yearsPaid\nyearsPaid: " + l_years_paid.strip() + "\n"
if l_newbie == '1':
mod_temp += "-\nreplace: newbie\nnewbie: FALSE\n\n"
else:
mod_temp += "\n"
print(mod_temp)

#open ldif
# open ldif
with open(sys.argv[1], 'r') as content:
ldif = content.read()
#split by user
getdn = string.split(ldif, 'dn: uid=')
for i in range(1,len(getdn)):
thisdn = getdn[i].split('\n')
newbie = 'NONE'
reserved = False
#split by users variables
for j in range(0,len(thisdn)):
x = thisdn[j].rstrip()
uid = thisdn[0].rstrip()
if 'reserved' in uid:
reserved = True
try:
if x.startswith("yearsPaid:"):
yearsPaid = str(int(x.split()[1])).strip()
elif x.startswith("newbie:"):
newbie = '1'
else: continue
except IndexError:
break
modifyTemplate(uid,yearsPaid,newbie,reserved)
LDIF = content.read()
# split by user
GETDN = LDIF.split('dn: uid=')
for i in range(1, len(GETDN)):
thisdn = GETDN[i].split('\n')
newbie = 'NONE'
reserved = False
# split by users variables
for j in range(0, len(thisdn)):
x = thisdn[j].rstrip()
uid = thisdn[0].rstrip()
if 'reserved' in uid:
reserved = True
try:
if x.startswith("yearsPaid:"):
years_paid = str(int(x.split()[1])).strip()
elif x.startswith("newbie:"):
newbie = '1'
else:
continue
except IndexError:
break
modify_template(uid, years_paid, newbie, reserved)

+ 0
- 2
ldap/ldapsearch.txt View File

@@ -1,2 +0,0 @@
ldapsearch -x -h ad.dcu.ie -D "CN=rblookup,OU=Service Accounts,DC=ad,DC=dcu,DC=ie" -w `cat /etc/ldap_dcu.secret` -b "OU=Students,DC=ad,DC=dcu,DC=ie" -s sub "(displayName=firstname surname)" cn gecos
ldapsearch -x -h ad.dcu.ie -D "CN=rblookup,OU=Service Accounts,DC=ad,DC=dcu,DC=ie" -w `cat /etc/ldap_dcu.secret` -b "OU=Students,DC=ad,DC=dcu,DC=ie" -s sub "(cn=username)" cn gecos

+ 0
- 10
ldap/ldif_founder_soc_fix.py View File

@@ -1,10 +0,0 @@
#!/usr/bin/python
import sys
for i in sys.stdin:
i = i.rstrip()
if i.startswith("yearsPaid:"):
print "yearsPaid:", int(i.split()[1]) + 9
elif i.startswith("newbie:"):
print "newbie: FALSE"
else:
print i

+ 8
- 8
ldap/newyear_ldif.py View File

@@ -1,12 +1,12 @@
#!/usr/bin/env python
""" generate new years ldif"""
import sys

for i in sys.stdin:
i = i.rstrip()
if i.startswith("yearsPaid:"):
print "yearsPaid:", int(i.split()[1]) - 1
elif i.startswith("newbie:"):
print "newbie: FALSE"
else:
print i

i = i.rstrip()
if i.startswith("yearsPaid:"):
print("yearsPaid:", int(i.split()[1]) - 1)
elif i.startswith("newbie:"):
print("newbie: FALSE")
else:
print(i)

+ 0
- 8
legacy/VM/create_vm View File

@@ -1,8 +0,0 @@
!#/bin/bash

if [ ! "`uname -n`" == "daniel" ]; then
echo for now this needs to be run on daniel
exit 1
fi

set IP=tail /srv/admin/

+ 0
- 243
legacy/VM/xen_deffault.conf View File

@@ -1,243 +0,0 @@

Values:

vncpasswd=NAME Password for VNC console on HVM domain.
vncviewer=no|yes Spawn a vncviewer listening for a vnc server in the
domain.
The address of the vncviewer is passed to the domain
on the kernel command line using
'VNC_SERVER=<host>:<port>'. The port used by vnc is
5500 + DISPLAY. A display value with a free port is
chosen if possible.
Only valid when vnc=1.
vncconsole=no|yes Spawn a vncviewer process for the domain's graphical
console.
Only valid when vnc=1.
name=NAME Domain name. Must be unique.
bootloader=FILE Path to bootloader.
bootargs=NAME Arguments to pass to boot loader
bootentry=NAME DEPRECATED. Entry to boot via boot loader. Use
bootargs.
kernel=FILE Path to kernel image.
ramdisk=FILE Path to ramdisk.
features=FEATURES Features to enable in guest kernel
builder=FUNCTION Function to use to build the domain.
memory=MEMORY Domain memory in MB.
maxmem=MEMORY Maximum domain memory in MB.
shadow_memory=MEMORY Domain shadow memory in MB.
cpu=CPU CPU to run the VCPU0 on.
cpus=CPUS CPUS to run the domain on.
rtc_timeoffset=RTC_TIMEOFFSET
Set RTC offset.
pae=PAE Disable or enable PAE of HVM domain.
timer_mode=TIMER_MODE
Timer mode (0=delay virtual time when ticks are
missed;
1=virtual time is always wallclock time.
acpi=ACPI Disable or enable ACPI of HVM domain.
apic=APIC Disable or enable APIC mode.
vcpus=VCPUS # of Virtual CPUS in domain.
vcpu_avail=VCPUS Bitmask for virtual CPUs to make available
immediately.
vhpt=VHPT Log2 of domain VHPT size for IA64.
cpu_cap=CAP Set the maximum amount of cpu.
CAP is a percentage that fixes the maximum amount of
cpu.
cpu_weight=WEIGHT Set the cpu time ratio to be allocated to the domain.
restart=onreboot|always|never
Deprecated. Use on_poweroff, on_reboot, and on_crash
instead.
Whether the domain should be restarted on exit.
- onreboot: restart on exit with shutdown code reboot
- always: always restart on exit, ignore exit code
- never: never restart on exit, ignore exit code
on_poweroff=destroy|restart|preserve|rename-restart
Behaviour when a domain exits with reason 'poweroff'.
- destroy: the domain is cleaned up as normal;
- restart: a new domain is started in place of the
old one;
- preserve: no clean-up is done until the domain is
manually
destroyed (using xm destroy, for example);
- rename-restart: the old domain is not cleaned up,
but is
renamed and a new domain started in its place.
on_reboot=destroy|restart|preserve|rename-restart
Behaviour when a domain exits with reason 'reboot'.
- destroy: the domain is cleaned up as normal;
- restart: a new domain is started in place of the
old one;
- preserve: no clean-up is done until the domain is
manually
destroyed (using xm destroy, for example);
- rename-restart: the old domain is not cleaned up,
but is
renamed and a new domain started in its place.
on_crash=destroy|restart|preserve|rename-restart
Behaviour when a domain exits with reason 'crash'.
- destroy: the domain is cleaned up as normal;
- restart: a new domain is started in place of the
old one;
- preserve: no clean-up is done until the domain is
manually
destroyed (using xm destroy, for example);
- rename-restart: the old domain is not cleaned up,
but is
renamed and a new domain started in its place.
blkif=no|yes Make the domain a block device backend.
netif=no|yes Make the domain a network interface backend.
tpmif=no|yes Make the domain a TPM interface backend.
disk=phy:DEV,VDEV,MODE[,DOM]
Add a disk device to a domain. The physical device is
DEV,
which is exported to the domain as VDEV. The disk is
read-only if MODE
is 'r', read-write if MODE is 'w'. If DOM is
specified it defines the
backend driver domain to use for the disk.
The option may be repeated to add more than one disk.
pci=BUS:DEV.FUNC Add a PCI device to a domain, using given params (in
hex).
For example 'pci=c0:02.1a'.
The option may be repeated to add more than one pci
device.
ioports=FROM[-TO] Add a legacy I/O range to a domain, using given
params (in hex).
For example 'ioports=02f8-02ff'.
The option may be repeated to add more than one i/o
range.
irq=IRQ Add an IRQ (interrupt line) to a domain.
For example 'irq=7'.
This option may be repeated to add more than one IRQ.
vfb=type={vnc,sdl},vncunused=1,vncdisplay=N,vnclisten=ADDR,display=DISPLAY,xauthority=XAUTHORITY,vncpasswd=PASSWORD
Make the domain a framebuffer backend.
The backend type should be either sdl or vnc.
For type=vnc, connect an external vncviewer. The
server will listen
on ADDR (default 127.0.0.1) on port N+5900. N
defaults to the
domain id. If vncunused=1, the server will try to
find an arbitrary
unused port above 5900. vncpasswd overrides the XenD
configured
default password.
For type=sdl, a viewer will be started automatically
using the
given DISPLAY and XAUTHORITY, which default to the
current user's
ones.
vif=type=TYPE,mac=MAC,bridge=BRIDGE,ip=IPADDR,script=SCRIPT,backend=DOM,vifname=NAME,rate=RATE,model=MODEL,accel=ACCEL
Add a network interface with the given MAC address
and bridge.
The vif is configured by calling the given
configuration script.
If type is not specified, default is netfront.
If mac is not specified a random MAC address is used.
If not specified then the network backend chooses
it's own MAC address.
If bridge is not specified the first bridge found is
used.
If script is not specified the default script is
used.
If backend is not specified the default backend
driver domain is used.
If vifname is not specified the backend virtual
interface will have name vifD.N
where D is the domain id and N is the interface id.
If rate is not specified the default rate is used.
If model is not specified the default model is used.
If accel is not specified an accelerator plugin
module is not used.
This option may be repeated to add more than one vif.
Specifying vifs will increase the number of
interfaces as needed.
vtpm=instance=INSTANCE,backend=DOM,type=TYPE
Add a TPM interface. On the backend side use the
given
instance as virtual TPM instance. The given number is
merely the
preferred instance number. The hotplug script will
determine
which instance number will actually be assigned to
the domain.
The associtation between virtual machine and the TPM
instance
number can be found in /etc/xen/vtpm.db. Use the
backend in the
given domain.
The type parameter can be used to select a specific
driver type
that the VM can use. To prevent a fully virtualized
domain (HVM)
from being able to access an emulated device model,
you may specify
'paravirtualized' here.
access_control=policy=POLICY,label=LABEL
Add a security label and the security policy
reference that defines it.
The local ssid reference is calculated when
starting/resuming the domain. At
this time, the policy is checked against the active
policy as well. This way,
migrating through save/restore is covered and local
labels are automatically
created correctly on the system where a domain is
started / resumed.
nics=NUM DEPRECATED. Use empty vif entries instead.
Set the number of network interfaces.
Use the vif option to define interface parameters,
otherwise
defaults are used. Specifying vifs will increase the
number of interfaces as needed.
root=DEVICE Set the root= parameter on the kernel command line.
Use a device, e.g. /dev/sda1, or /dev/nfs for NFS
root.
extra=ARGS Set extra arguments to append to the kernel command
line.
ip=IPADDR Set the kernel IP interface address.
gateway=IPADDR Set the kernel IP gateway.
netmask=MASK Set the kernel IP netmask.
hostname=NAME Set the kernel IP hostname.
interface=INTF Set the kernel IP interface name.
dhcp=off|dhcp Set the kernel dhcp option.
nfs_server=IPADDR Set the address of the NFS server for NFS root.
nfs_root=PATH Set the path of the root NFS directory.
device_model=FILE Path to device model program.
fda=FILE Path to fda
fdb=FILE Path to fdb
serial=FILE Path to serial or pty or vc
monitor=no|yes Should the device model use monitor?
localtime=no|yes Is RTC set to localtime?
keymap=FILE Set keyboard layout used
usb=no|yes Emulate USB devices?
usbdevice=NAME Name of USB device to add?
guest_os_type=NAME Guest OS type running in HVM
stdvga=no|yes Use std vga or cirrhus logic graphics
isa=no|yes Simulate an ISA only system?
boot=a|b|c|d Default boot device
nographic=no|yes Should device models use graphics?
soundhw=audiodev Should device models enable audio device?
vnc Should the device model use VNC?
vncdisplay VNC display to use
vnclisten Address for VNC server to listen on.
vncunused Try to find an unused port for the VNC server.
Only valid when vnc=1.
sdl Should the device model use SDL?
display=DISPLAY X11 display to use
xauthority=XAUTHORITY
X11 Authority to use
uuid xenstore UUID (universally unique identifier) to use.
One
will be randomly generated if this option is not set,
just like MAC
addresses for virtual network interfaces. This must
be a unique
value across the entire cluster.
on_xend_start=ignore|start
Action to perform when xend starts
on_xend_stop=ignore|shutdown|suspend
Behaviour when Xend stops:
- ignore: Domain continues to run;
- shutdown: Domain is shutdown;
- suspend: Domain is suspended;


+ 0
- 104
legacy/faststorage_add.pl View File

@@ -1,104 +0,0 @@
#!/usr/bin/perl
use warnings;
use strict;

# Script for adding fast storage for a user
# Last modified 9 Jan 2007, werdz@redbrick.dcu.ie

#############################
# Default settings
#############################
my $softlimit = 300000;
my $hardlimit = 330000;
my $softblocks = 800000;
my $hardblocks = 1000000;
#############################

# General configuration
my $faststorage_location = "/fast-storage/users";
my $faststorage_device = "/dev/sda7";

# Check for command line arguments
usage() unless $ARGV[0];

my $username = $ARGV[0];

if($ARGV[1]) {
$softlimit = $ARGV[1];
$hardlimit = int($softlimit * 1.10);
}

if($ARGV[2]) {
$softblocks = $ARGV[2];
$hardblocks = int($softblocks * 1.25);
}

# Determine any extra information we'll need

my $user_letter = lc(substr($username,0,1));
my $groups_output = `id $username`;
#print $groups_output;
$groups_output =~ m/uid=\d*\(.*?\) gid=\d*\((.*?)\).*$/;
my $usergroup = $1;

# Check if the user already has fast storage space

if( -e $faststorage_location . "/" . $user_letter . "/" . $username) {
print "User " . $username . " already appears have a fast storage account at:\n";
print $faststorage_location . "/" . $user_letter . "/" . $username . "\n\n";
exit(1); # Unsuccessful error code
}

# Build commands

my $mkdir_cmd = "mkdir -p " . $faststorage_location . "/" . $user_letter . "/" . $username;
my $chmod_cmd = "chmod 700 " . $faststorage_location . "/" . $user_letter . "/" . $username;
my $chown_cmd = "chown $username:$usergroup $faststorage_location/$user_letter/$username";
my $quota_cmd = "setquota -u " . $username . " " . $softlimit . " " . $hardlimit . " " . $softblocks . " " . $hardblocks . " " . $faststorage_device;

# Print out a summary of what will be done.
print "User does not appear to have fast storage space.\n";
print "Summary of what will be done:\n\n";

print $mkdir_cmd . "\n" . $chmod_cmd . "\n" . $chown_cmd . "\n" . $quota_cmd . "\n\n";

# Ask the user if this is acceptable.
my $valid_answer = 0;
my $user_answer;
while(!$valid_answer) {
print "Is this alright? (Y/N): ";
$user_answer = lc(<STDIN>);
chomp $user_answer;
if($user_answer eq 'y' || $user_answer eq 'n') {
$valid_answer = 1;
}
}

# User says no.
if($user_answer eq 'n') {
print "Aborted by user.\n";
exit(1);
}

# Approved by user.. continue.

print "Creating directory...\n";
`$mkdir_cmd`;
print "Setting permissions...\n";
`$chmod_cmd`;
print "Setting ownership...\n";
`$chown_cmd`;
print "Setting quota...\n";
`$quota_cmd`;
print "Done.\n";
exit(0);

#####################################################
#####################################################

sub usage {
my $usage = "Fast storage script\n";
$usage .= "Usage: faststorage_add.pl username [custom quota size] [custom block limit]\n";
print $usage;
exit(1); # Unsuccessful error code
}

+ 0
- 80
legacy/pcp View File

@@ -1,80 +0,0 @@
#!/usr/bin/ksh
#
# PCP (PID con Port)
# v1.09 30/05/2009 Sam Nelson sam @ unix.ms
#
# If you have a Solaris 8, 9 or 10 box and you can't
# install lsof, try this. It maps PIDS to ports and vice versa.
# It also shows you which peers are connected on which port.
# Wildcards are accepted for -p and -P options.
#
# Many thanks Daniel Trinkle trinkle @ cs.purdue.edu
# for the help, much appreciated.
i=0
while getopts :p:P:a opt
do
case "${opt}" in
p ) port="${OPTARG}";i=3;;
P ) pid="${OPTARG}";i=3;;
a ) all=all;i=2;;
esac
done
if [ $OPTIND != $i ]
then
echo >&2 "usage: $0 [-p PORT] [-P PID] [-a] (Wildcards OK) "
exit 1
fi
shift `expr $OPTIND - 1`
if [ "$port" ]
then
# Enter the port number, get the PID
#
port=${OPTARG}
echo "PID\tProcess Name and Port"
echo "_________________________________________________________"
for proc in $(ptree -a | awk '/ptree/ {next} {print $1};')
do
result=$(pfiles $proc 2> /dev/null| egrep "port: $port$")
if [ ! -z "$result" ]
then
program=$(ps -fo comm= -p $proc)
echo "$proc\t$program\t$port\n$result"
echo "_________________________________________________________"
fi
done
elif [ "$pid" ]
then
# Enter the PID, get the port
#
pid=$OPTARG
# Print out the information
echo "PID\tProcess Name and Port"
echo "_________________________________________________________"
for proc in $(ptree -a | awk '/ptree/ {next} $1 ~ /^'"$pid"'$/ {print $1};')
do
result=$(pfiles $proc 2> /dev/null| egrep "port:")
if [ ! -z "$result" ]
then
program=$(ps -fo comm= -p $proc)
echo "$proc\t$program\n$result"
echo "_________________________________________________________"
fi
done
elif [ $all ]
then
# Show all PIDs, Ports and Peers
#
echo "PID\tProcess Name and Port"
echo "_________________________________________________________"
for proc in `ptree -a | sort -n | awk '/ptree/ {next} {print $1};'`
do
out=$(pfiles $proc 2>/dev/null| egrep "port:")
if [ ! -z "$out" ]
then
name=$(ps -fo comm= -p $proc)
echo "$proc\t$name\n$out"
echo "_________________________________________________________"
fi
done
fi
exit 0

+ 0
- 21
legacy/twitter_rss.sh View File

@@ -1,21 +0,0 @@
#!/bin/bash

export http_proxy="http://proxy.dcu.ie:8080"
WEBDIR="/webtree/redbrick/htdocs"
TMPDIR="/tmp"
FILE="twitter.rss"

if [ ! -d $WEBDIR ]; then
exit 1
fi

/usr/bin/wget -O $TMPDIR/$FILE http://twitter.com/statuses/user_timeline/28599864.rss &> /dev/null

# failure test
if [ $? -ne 0 ]; then
exit 0
fi

sed -i 's/RedBrickDCU: //' $TMPDIR/$FILE
mv $TMPDIR/$FILE $WEBDIR/$FILE
chmod 644 $WEBDIR/$FILE

+ 0
- 11
legacy/update_pkgsrc.sh View File

@@ -1,11 +0,0 @@
#!/bin/bash

# Updates the pkgsrc ports tree.
# werdz@redbrick.dcu.ie, 18/11/09

export HTTP_PROXY=http://proxy.dcu.ie:8080
export CVS_RSH=ssh
export PATH=/usr/pkg/bin:/usr/pkg/sbin:$PATH

cd /usr/pkgsrc
tsocks cvs update -dP

+ 0
- 30
mysql-slave-permissions.sh View File

@@ -1,30 +0,0 @@
#!/bin/bash

#date=`/bin/date +%Y%m%d`
date=20080830
success=0
loops=0


while [ $success -eq 0 ]; do

success=`grep -c success /backup/mysql/$date/summary`

if [ $success -gt 0 ]; then
files=`find /backup/mysql/$date/tree/dumps/ -type f -printf "%P \n"`

for file in $files; do
username=${file%.sql}
group=`id -g $username`
chown $username:$group /backup/mysql/$date/tree/dumps/$file

done
elif [ $loops -gt 12 ]; then
exit 1

els
$loops++
sleep 1800
fi

done

+ 0
- 37
not_a_user_db.py View File

@@ -1,37 +0,0 @@
#!/usr/bin/python
import string, os, sys
import subprocess

def getCourses(db):
result = ''
p = subprocess.Popen('./rbsearch -uid '+str(db)+' | grep yearsPaid', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
p.daemon=True
for line in p.stdout.readlines():
result += line
retval = p.wait()

if '1' in result:
return False
else:
return True

#start processing input
filenameGiven = True
try:
filename = sys.argv[1]
except IndexError,e:
print 'Usage: not_a_user_db.py <filename>'
filenameGiven = False

#check if filename of input has been given
if(filenameGiven):
f = open(filename)
lines = [line.strip() for line in open(filename)]
f.close()

for l in lines:
if(getCourses(l)):
print l




mysql_add → perl/mysql_add View File


+ 0
- 2
postgres_add View File

@@ -1,2 +0,0 @@
#!/bin/bash
su postgres -c "createuser --no-superuser --no-createdb --no-createrole $1; createdb $1 -O $1"

+ 118
- 0
python/groupmail.py View File

@@ -0,0 +1,118 @@
#!/usr/bin/python3

"""
-maK
This is a script to send a mail to a group
defined by an ldap search
or simply send a singular mail

use ./groupmail -h
"""
import smtplib
import argparse
import os

def sendmail(frm, to_email, subject, body, cc_email=''):
""" Send email"""
msg = '\r\n'
msg.join(('From: %s' % frm,
'To: %s' % to_email,
'CC: %s' % cc_email,
'Subject: %s' % subject,
'',
'%s' % body))
try:
smtp = smtplib.SMTP('mailhost.redbrick.dcu.ie')
smtp.sendmail(frm, to_email, msg)
smtp.quit()
except smtp.SMTPRecipientsRefused:
print('Error sending mail to ' + to_email)
except smtp.SMTPHeloError:
print('The server didn’t reply properly to the HELO greeting.')
except smtp.SMTPSenderRefused:
print('The server didn’t accept the from address')
except smtp.SMTPDataError:
print('The server replied with an unexpected error code')
except smtp.SMTPNotSupportedError:
print('utf8 not supported by server')

def mailgroup(ldif, frm, subject, body, prnt):
""" email groups"""
to_mail = ldif.split('dn: uid=')
ldap_cn = ''
altmail = ''
uid = ''
for j in range(1, len(to_mail)):
credentials = to_mail[j].split('\n')
for i in credentials:
if i.startswith('uid: '):
uid = i.split()[1]
if i.startswith('cn: '):
ldap_cn = i.split('cn: ')[1]
if i.startswith('altmail: '):
altmail = i.split()[1]
if prnt:
print(uid + ' - ' + ldap_cn + ' : ' + altmail)
else:
# Send mail to each
print('Send mail to ' + ldap_cn + ' using ' + altmail + ' (y|n)?')
send = input('default(y): ')
if(send == 'n') or (send == 'N'):
print('Mail not sent to ' + ldap_cn + ' using ' + altmail + '\n')
else:
sendmail(frm, altmail.strip(), subject, body)
print('Mail sent to ' + ldap_cn + ' using ' + altmail + '\n')

def check_args(args):
"""check args for sending"""
if(args.GROUPS is None and args.FROM is not None and args.TO is not None and
args.SUBJECT is not None and args.MSG is not None):
return not args.PRINT
return False

def main():
"""Main method"""
parser = argparse.ArgumentParser(description='Used to mail an ldap group/groups')
parser.add_argument('-g', dest='GROUPS', type=str,
help='Specify groups or singular group.\
(eg. club or club,society,founders,redbrick)')
parser.add_argument('-p', dest='PRINT', action='store_true',
help='Only print details - Do not send')
parser.add_argument('-f', dest='FROM', type=str, help='Who the mail is from.')
parser.add_argument('-cc', dest='CC', type=str, help='cc all mails to.')
parser.add_argument('-m', dest='MSG', type=str,
help='Location of Message to be sent (text file etc)')
parser.add_argument('-t', dest='TO', type=str, help='Who singular mail is To.')
parser.add_argument('-s', dest='SUBJECT', type=str, help='Subject of mail.')
args = parser.parse_args()

if args.GROUPS is not None:
if ',' in args.GROUPS:
search_params = args.GROUPS.split(',')
else:
search_params = args.GROUPS
ldapsearch = 'ldapsearch -D cn=root,ou=ldap,o=redbrick -y /etc/ldap.secret -xLLL '
if isinstance(search_params, str):
ldapsearch += '"(objectClass=' + search_params + ')" uid cn altmail'
else:
ldapsearch += '"(|'
for i in search_params:
ldapsearch += '(objectClass=' + i + ')'
ldapsearch += ')" uid cn altmail'

ldif = os.popen(ldapsearch).read()
if args.FROM is not None and args.SUBJECT is not None and args.MSG is not None:
mailgroup(ldif, args.FROM, args.SUBJECT, args.MSG, args.PRINT)
else:
mailgroup(ldif, '', '', '', args.PRINT)
exit()

if args.MSG is not None:
with open(args.MSG, 'r') as content:
args.MSG = content.read()

if check_args(args):
sendmail(args.FROM, args.TO, args.SUBJECT, args.MSG, args.CC)

if __name__ == '__main__':
main()

+ 33
- 0
python/not_a_user_db.py View File

@@ -0,0 +1,33 @@
#!/usr/bin/python3
"""Check if db is owned by a user"""
import sys
import subprocess

def get_courses(db_name):
"""Get users course"""
result = ''
proc = subprocess.Popen('../bash/rbsearch -uid ' + str(db_name) + ' | grep yearsPaid',
shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
proc.daemon = True
for line in proc.stdout.readlines():
result += line
proc.wait()

if '1' in result:
return False
return True

# start processing input
if sys.argv[1]:
try:
FILENAME = sys.argv[1]
FILE = open(FILENAME)
LINES = [line.strip() for line in FILE]
FILE.close()
for l in LINES:
if get_courses(l):
print(l)
except IndexError as err:
print('Usage: not_a_user_db.py <filename>')
else:
print('Usage: not_a_user_db.py <filename>')

+ 29
- 0
python/yearspaid_mak_fix.py View File

@@ -0,0 +1,29 @@
#!/usr/bin/python3
"""
Fixing shit I fucked.
Running on the output of this search

ldapsearch -D cn=root,ou=ldap,o=redbrick -y /etc/ldap.secret -xLLL "(|(objectClass=club)
(objectClass=society)(objectClass=projects)(objectClass=redbrick)(objectClass=dcu)
"""
import sys

def modify_template(user_id):
"""print modify ldif template"""
ldap_dn = 'dn: uid=' + user_id.strip()
ldap_dn += "\nchangetype: modify\ndelete: yearsPaid\n\n"
print(ldap_dn)

# open ldif
with open(sys.argv[1], 'r') as content:
LDIF = content.read()
# split by user
GETDN = LDIF.split('dn: uid=')
for i in GETDN:
try:
thisdn = i.split('\n')
uid = thisdn[0]
if uid:
modify_template(uid)
except IndexError:
continue

+ 0
- 99
rbsearch View File

@@ -1,99 +0,0 @@
#!/bin/bash

# Quick ldap search tool
# ver 0.1 sonic - I will never ever update this
# ver 0.2 koffee - quick update & shell checking
# ver 0.3 butlerx - add support for dcu AD

SCRIPTNAME="rbsearch"
EMAIL="bill.gates@hotmail.com"
USERNAME="microbg"
FULLNAME="Bill Gates"

SEARCH="ldapsearch -D cn=root,ou=ldap,o=redbrick -xLLL -y /etc/ldap.secret"

function dcusearch () {
if [ ! -z $2 ]; then
SEARCH="$1 $2"
else
SEARCH=$1
fi
ldapsearch -x -h ad.dcu.ie -D "CN=rblookup,OU=Service Accounts,DC=ad,DC=dcu,DC=ie" -w $(</etc/ldap_dcu.secret) -b "OU=Students,DC=ad,DC=dcu,DC=ie" -s sub "($SEARCH)" cn gecos mail
}

case $1 in
-update)
if [ ! -z $3 ]; then
$SEARCH "cn=*$2*$3" uid yearsPaid loginShell
else
echo "Usage: $SCRIPTNAME -fullname $FULLNAME"
fi

;;
-altmail)
$SEARCH "altmail=$2" uid
;;
-uid)
$SEARCH "uid=$2"
;;
-id)
$SEARCH "id=$2" uid
;;
-name)
$SEARCH "cn=*$2*" uid
;;
-nick)
$SEARCH "gecos=*$2*" uid
;;
-fullname)
if [ ! -z $3 ]; then
$SEARCH "cn=*$2*$3" uid
else
echo "Usage: $SCRIPTNAME -fullname $FULLNAME"
fi
;;
-newbie)
$SEARCH "newbie=TRUE" uid
;;
-dcu)
case $2 in
username)
SEARCH="cn=$3"
dcusearch $SEARCH
;;
fullname)
if [ ! -z $4 ]; then
SEARCH="displayName=$3 $4"
dcusearch $SEARCH
else
echo "Usage: $SCRIPTNAME -dcu fullname $FULLNAME"
fi
esac
;;
-h)
echo "Usage: $SCRIPTNAME [-altmail] [-uid] [-id] [-name] -[nick] -[fullname] query"
echo "eg. $SCRIPTNAME -altmail $EMAIL"
echo " $SCRIPTNAME -uid $USERNAME"
echo " $SCRIPTNAME -fullname $FULLNAME"
echo " $SCRIPTNAME -update $USERNAME"
echo " $SCRIPTNAME -dcu username $USERNAME"
echo " $SCRIPTNAME -dcu fullname $FULLNAME"
echo ""
echo "Only fullname takes 2 arguments."
echo "All results will give just uid(s) apart from [-uid]"
echo "[-uid] prints all ldap info for that uid"
;;
*)
echo "Usage: $SCRIPTNAME [-altmail] [-uid] [-id] [-name] [-nick] [-fullname] [-dcu [username] [fullname]] query"
echo "eg. $SCRIPTNAME -altmail $EMAIL"
echo " $SCRIPTNAME -uid $USERNAME"
echo " $SCRIPTNAME -fullname $FULLNAME"
echo " $SCRIPTNAME -update $USERNAME"
echo " $SCRIPTNAME -dcu username $USERNAME"
echo " $SCRIPTNAME -dcu fullname $FULLNAME"
echo ""
echo "Only fullname takes 2 arguments."
echo "All results will give just uid(s) apart from [-uid]"
;;
esac


+ 0
- 31
yearspaid_mak_fix.py View File

@@ -1,31 +0,0 @@
#!/usr/bin/python
import sys,string

"""
Fixing shit I fucked.

Running on the output of this search

ldapsearch -D cn=root,ou=ldap,o=redbrick -y /etc/ldap.secret -xLLL "(|(objectClass=club)(objectClass=society)(objectClass=projects)(objectClass=redbrick)(objectClass=dcu)(objectClass=intersoc)(objectClass=founders))"

"""

#print modify ldif template
def modifyTemplate(uid):
dn = 'dn: uid='+uid.strip()
dn += "\nchangetype: modify\ndelete: yearsPaid\n\n"
print dn

#open ldif
with open(sys.argv[1], 'r') as content:
ldif = content.read()
#split by user
getdn = string.split(ldif, 'dn: uid=')
for i in getdn:
try:
thisdn = string.split(i,'\n')
uid = thisdn[0]
if(len(uid) > 0):
modifyTemplate(uid)
except IndexError:
continue

Loading…
Cancel
Save