david/scripts-archive
david
/
scripts-archive
Archived
1
0
Fork 0

initial commit, added everything old from my scripts repo

This commit is contained in:
david 2022-04-16 20:25:43 +02:00
commit 5e60ee959c
77 changed files with 5982 additions and 0 deletions

41
README.please Normal file
View File

@ -0,0 +1,41 @@
this is my little mobot project.
the concept is not to spend hundreds of hours to implement some massive
monitoring tool like nagios or something like this.
instead i want to use some simple message/notification scripts
which exactly tell me what i need to know.
the first thing i have here is the df bot. it sends me a short jabber message
when one or more disks on the serving machine reaching a preconfigured threshold
(example: 90% disk usage).
another tool i find really useful is the pingbot (ping.sh)
it works pretty much the same as the dfbot.
feel free to use or improve this handy tools!
=== install notes ===
1. copy the scrip somewhere on your machine
you get the df.sh on gitorious.org
http://gitorious.org/sn/scripts/trees/master/mobots/df.sh
2. create the configfile
use the df.conf.sample to create a config and put this file anywhere on the same machine
http://gitorious.org/sn/scripts/trees/master/mobots/df.conf.sample
3. create a cronjob for it
add a line like this to your /etc/crontab
*/2 * * * * root /bin/bash --login /path/to/the/script/df.sh /path/to/configfile/df.conf >> /path/to/logfile/df.log
or (if you use the default configpath /etc/mobots)
*/5 * * * * root /bin/bash --login /path/to/script/df.sh >> /var/log/mobots/df.log
the logdirectory must exist
after this you have to restart your cron with something like
service cron restart
of course there are several ways to create a cronjob but this is probably the easiest way
any questions? mail me! (david@socialnerds.org)

144
bandwidth.sh Executable file
View File

@ -0,0 +1,144 @@
#!/bin/bash
# script to test bandwidth to ssh server
# it copies a 10MB file to the server and
# loads it back down again.
# usage: bandwidth user@server
# if no server is applied a default server is used
# defaults
sshserver=birdofprey
sshuser=david
sshpath="/tmp"
localpath="/tmp"
file=$RANDOM
size=10 #MB
silent=1
# config
if [ $# -ne 0 ]; then
sshuser=$(echo $1 | sed 's/@.*//')
sshserver=$(echo $1 | sed 's/.*@//')
if [ $# -gt 1 ]; then
echo "too much arguments. exiting."
exit 1
fi
if [ $silent -ne 1 ]; then
echo "using custom server. ($sshuser@$sshserver)"
fi
else
if [ $silent -ne 1 ]; then
echo "using default server. ($sshuser@$sshserver)"
fi
fi
# preflight
command -v scp &> /dev/null
if [[ $? -ne 0 ]]; then
echo "scp must be installed first. exiting."
exit 1
fi
command -v ssh &> /dev/null
if [[ $? -ne 0 ]]; then
echo "ssh must be installed first. exiting."
exit 1
fi
command -v python &> /dev/null
if [[ $? -ne 0 ]]; then
echo "python must be installed first. exiting."
exit 1
fi
# create file
if [ $silent -ne 1 ]; then
echo "creating $size MB file."
fi
dd if=/dev/zero of=$localpath/$file bs=$(($size*1024*1024)) count=1 &> /dev/null
if [[ $? -ne 0 ]]; then
echo "cannot create file. ($localpath/$file)"
exit 1
fi
# upload file
if [ $silent -ne 1 ]; then
echo "uploading file to $sshserver"
fi
scp -v $localpath/$file $sshuser@$sshserver:$sshpath/$file &> $localpath/bandwidth_scplogup
if [ $? -ne 0 ]; then
echo "error while uploading file. exiting."
echo "there might be information in the scp log. ($localpath/bandwidth_scplogup)"
# remove local file
rm $localpath/$file
if [[ $? -ne 0 ]]; then
echo "cannot delete local file. exiting. ($localpath/$file) - you must fix this!!"
else
if [ $silent -ne 1 ]; then
echo "local file has been deleted."
fi
fi
exit 1
fi
result=$(cat $localpath/bandwidth_scplogup | grep "Bytes per second" | awk '{print $5}' | sed 's/\,//')
result=$(echo $result | sed 's/\..*//')
echo "UPLOAD: $(($result * 8 / 1024)) kbit/s"
rm $localpath/bandwidth_scplogup
# download file
if [ $silent -ne 1 ]; then
echo "downloading file from $sshserver."
fi
scp -v $sshuser@$sshserver:$sshpath/$file $localpath/$file &> $localpath/bandwidth_scplogdown
if [ $? -ne 0 ]; then
echo "error while downloading file. exiting."
echo "there might be information in the scp log. ($localpath/bandwidth_scplogdown)"
# remove remote file
ssh $sshuser@$sshserver rm $sshpath/$file &> /dev/null
if [[ $? -ne 0 ]]; then
echo "cannot remove remote file. ($sshpath/$file) - you must fix this!!"
sleep 5
else
if [ $silent -ne 1 ]; then
echo "remote file removed."
fi
fi
exit 1
fi
result=$(cat $localpath/bandwidth_scplogdown | grep "Bytes per second" | awk '{print $7}' | sed 's/\,//')
result=$(echo $result | sed 's/\..*//')
echo "DOWNLOAD: $(($result * 8 / 1024)) kbit/s"
rm $localpath/bandwidth_scplogdown
# remove remote file
ssh $sshuser@$sshserver rm $sshpath/$file &> /dev/null
if [[ $? -ne 0 ]]; then
echo "cannot remove remote file. ($sshpath/$file) - you must fix this!!"
sleep 5
else
if [ $silent -ne 1 ]; then
echo "remote file removed."
fi
fi
# remove local file
rm $localpath/$file
if [[ $? -ne 0 ]]; then
echo "cannot delete local file. exiting. ($localpath/$file) - you must fix this!!"
exit 1
else
if [ $silent -ne 1 ]; then
echo "local file has been deleted."
fi
exit 0
fi
if [ $silent -ne 1 ]; then
echo "all done. exiting."
fi
exit 0

264
bashlib Normal file
View File

@ -0,0 +1,264 @@
# bashlib
# frequently used shell/bash functions
# **** check for root privileges ****
amiroot()
{
local user=$(whoami)
case $1 in
not) #not needed
log debug "amiroot - checking for unnecessary root privileges" #debug log
if [ "$(whoami)" = "root" ]; then
log error "amiroot - you probably should not run this as root. it could mess up your karma."
exit 1
fi
;;
*) #required
log debug "amiroot - checking for necessary root privileges" #debug log
if [ "$(whoami)" != "root" ]; then
log error "amiroot - $USER, you need to gain root privileges to do this."
exit 1;
fi
;;
esac
}
# **** generate timestamp ****
gettimestamp()
{
if [ -z $1 ]; then
date '+%Y%m%d%H%M'
elif [ $1 = "nice" ]; then
date '+%d.%m.%Y %H:%M'
elif [ $1 = "short" ]; then
date '+%Y%m%d'
fi
}
# **** bashtrap ****
bashtrap()
{
log debug "bashtrap - triggered"
clear
echo "CTRL+C detected.. exiting!"
exit 1
}
# this gives your bash scripts the ability to get updated
# basically it does a simple git pull
# **** help ****
# global vars needed: $repopath, $bashlibpath
# it depends on bashlib
# **** update (git pull) ****
update()
{
# checking for root privileges
amiroot
# update start message
log info "update - starting update of $logwhat and bashlib"
# bashlib update
cd $bashlibpath
git pull origin master | grep "files changed"
local returncode=$?
if [ $returncode = "0" ]; then
log info "update - bashlib has been updated"
else
log info "update - bashlib is already up-to-date"
fi
# update
cd $repopath
git pull origin master | grep "files changed"
local returncode=$?
if [ $returncode = "0" ]; then
log info "update - $logwhat has been updated"
else
log info "update - $logwhat is already up-to-date"
fi
}
# **** dialog helper ****
graph()
{
local bgtitle="kvm-tools $version | $1"
if [ $2 = "--inputbox" ]; then
local size="7 80"
elif [ $2 = "--yesno" ]; then
local size="20 80"
elif [ $2 = "--fselect" ]; then
local size="12 80"
else
local size="20 80 14"
fi
dialog --backtitle "$bgtitle" --no-cancel "$2" "$3" $size $4 2> /tmp/dialog
local returncode=$?
clear
dialogresult=$(cat /tmp/dialog)
rm /tmp/dialog
return $returncode
}
# log engine
# **** help ****
# this is basically a collection of bash functions
# for making a decent logging in a bash script
# amazingly easy.
#
# in order to use this little logging script
# you need to have some global variables defined
# loglevel=<0-4>
# 0 -- no logging
# 1 -- just errors
# 2 -- errors & warnings
# 3 -- even infos (something like "user was created")
# 4 -- debug (more than everything)
#
# logfile="/path/to/logfile.log"
# well.. should be understandable..
#
# logwhat="kvm-tools"
# tells the engine what is actually been logged (example: name of calling script)
# just used for syslog
#
# log2syslog="0|1"
# (de)activates logging to the syslog deamen
#
# log2stdout="0|1"
# (de)activates logging to stdout
# useful if you don't want to deal with output in your script
#
# log2file="0|1"
# (de)activates logging to logfile
#
#
# usage:
# log error|warning|info|debug "log message"
# **** log function ****
log()
{
# getting local hostname
local hostname=$(cat /etc/hostname)
# if no loglevel is defined the script will end
if [ -z $loglevel ]; then
echo "logengine[error]: no loglevel defined"
exit 1
# if loglevel is 0, skip logging
elif [ $loglevel = "0" ]; then
# logging is disabled
return 0
# loglevel has to be something between 0 and 5
elif [ ! $loglevel -gt "0" -o ! $loglevel -lt "5" ]; then
# loglevel unknown
echo "logengine[error]: unknown loglevel"
exit 1
fi
# stdout routine
if [ -z $log2stdout ]; then
log2stdout="0"
elif [ $log2stdout = "0" ]; then
# stdout is disabled
:
elif [ $log2stdout = "1" ]; then
# here goes the actual logging process (stdout)
if [ $1 = "error" -a $loglevel -gt "0" ]; then
# errors
echo "[$1]: $2"
elif [ $1 = "warning" -a $loglevel -gt "1" ]; then
# warnings
echo "[$1]: $2"
elif [ $1 = "info" -a $loglevel -gt "2" ]; then
# informational
echo "[$1]: $2"
elif [ $1 = "debug" -a $loglevel -gt "3" ]; then
# debug messages
echo "[$1]: $2"
fi
fi
# syslog routine
if [ -z $log2syslog ]; then
log2syslog="0"
elif [ $log2syslog = "0" ]; then
# syslog is disabled
:
elif [ -z $logwhat ]; then
# for syslogging logwhat has to be defined
echo "logengine[error]: logwhat not defined"
elif [ $log2syslog = "1" ]; then
# here goes the actual logging process (syslog)
if [ $1 = "error" -a $loglevel -gt "0" ]; then
# errors
logger -t "$logwhat[$1]" "$2"
elif [ $1 = "warning" -a $loglevel -gt "1" ]; then
# warnings
logger -t "$logwhat[$1]" "$2"
elif [ $1 = "info" -a $loglevel -gt "2" ]; then
# informational
logger -t "$logwhat[$1]" "$2"
elif [ $1 = "debug" -a $loglevel -gt "3" ]; then
# debug messages
logger -t "$logwhat[$1]" "$2"
fi
fi
# logfile routine
if [ -z $log2file ]; then
log2file="0"
elif [ $log2file = "0" ]; then
# file is disabled
:
elif [ $log2file = "1" ]; then
if [ -z $logfile ]; then
# if no logfile is defined the script will end
echo "logengine[error]: no logfile defined"
exit 1
elif ! [ -a $logfile ]; then
echo "logengine[warning]: logfile not found"
echo "logengine[info]: creating new logfile"
touch $logfile
if [ $? != 0 ]; then
# probably a permission denied error
echo "logengine[error]: could not create logfile."
exit 1
fi
fi
# here goes the actual logging process (logfile)
if [ $1 = "error" -a $loglevel -gt "0" ]; then
# errors
echo "$(gettimestamp nice) [$1]: $2" >> $logfile
elif [ $1 = "warning" -a $loglevel -gt "1" ]; then
# warnings
echo "$(gettimestamp nice) [$1]: $2" >> $logfile
elif [ $1 = "info" -a $loglevel -gt "2" ]; then
# informational
echo "$(gettimestamp nice) [$1]: $2" >> $logfile
elif [ $1 = "debug" -a $loglevel -gt "3" ]; then
# debug messages
echo "$(gettimestamp nice) [$1]: $2" >> $logfile
fi
fi
}

14
check_glue_records.sh Executable file
View File

@ -0,0 +1,14 @@
#!/bin/sh
S=${IFS}
IFS=.
for P in $1; do
TLD=${P}
done
IFS=${S}
echo "TLD: ${TLD}"
DNSLIST=$(dig +short ${TLD}. NS)
for DNS in ${DNSLIST}; do
echo "Checking ${DNS}"
dig +norec +nocomments +noquestion +nostats +nocmd @${DNS} $1 NS
done

View File

@ -0,0 +1 @@
ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA9Kk/PiaCOR4D5wNv+0NI1tnYl81pdR9zEK4E997cGyWwDUhBFnlbbHJdBsH55xMDZV59pyVp4drFmt+QKplIPijSh5uJavjYENVtrPJHTrHOOd6B05rdruyaGxLBxOMLmwA/+e/U/Q0Nj17wHs4LCxr4oe+LlzaeSKLb2ZrSDhgrYc0CAQg58ISDRVUDXDXwaHlsJUAm1f3jHb4l6gVX8qhdJRT1aqjNtERG+uWJsZZIOIuHLrSqOhJvKif4xdc5fenVH0nkeAyrVZJJLrq33Bk/8i8z/ZiyM4/uUOfPwymI7aVNREXrEKTWG4GmgLugFDOyk563qqhljx97TmUJzQ== root@karlmoik

43
clonebackup/clone.sh Executable file
View File

@ -0,0 +1,43 @@
#!/bin/bash
# get mac address
net=192.168.19.
ifs="eth0 eth1 eth2 eth3 eth4"
# get the configuration with ip
string=$(ip addr | grep "inet $net")
set -- $ifs
for var in "$@"; do
if [[ $string == "" ]]; then
echo "error: no interface configured to $net, exiting"
exit 1
else
if [[ $string == *$var* ]]; then
macstring=$(ip addr show eth0 | grep ether)
fi
fi
done
# get mac address
mac=${macstring:15:17}
#echo "MAC Address: $mac"
# get the hostname from the list
hostnamestring=$(cat mac2hostname.lst | grep $mac)
hostname=${hostnamestring:18}
#echo "Hostname: $hostname"
# generate imagename
imagename=$hostname"_$(echo $(date "+%d_%m_%C%y"))"
#echo "Imagename: $imagename"
echo $imagename
# starting clonezilla imaging process
/opt/drbl/sbin/ocs-sr -q2 -j2 -gs -z1 -i 0 -p reboot savedisk "$imagename" "sda"
# also possible "sda sdb"
# end of script
exit 0

View File

@ -0,0 +1,9 @@
# shares to mount
# example: user@host:/smbshare/directory;password
# no symbols allowed in sharenames
Administrator@192.168.19.20:/vrpack/VRProjects/;pentium4711
#Administrator@192.168.19.20:/ssd\ \(s\)/Gigapixel/;pentium4711
Administrator@192.168.19.20:/vrprojects/;pentium4711
Administrator@192.168.19.100:/software/;pentium4711

98
clonebackup/filebackup.sh Executable file
View File

@ -0,0 +1,98 @@
#!/bin/bash
# # # # # # # # # # # # # # # #
# #
# DeepSpace File Backup #
# v0.1 #
# david@socialnerds.org #
# #
# # # # # # # # # # # # # # # #
## README SECTION
##
## nothing to read yet :-)
##
##
# definitions
configfile="/srv/scripts/filebackup.conf" # use absolut path
mountpath="/mnt"
backuppath="/srv/filebackup"
# gen timestamp
timestamp=$(echo $(date "+%d_%m_%C%y"))
# am i root
if [ "$(whoami)" != "root" ]; then
echo "error: only root can do this"
exit 1;
fi
# starting message with timestamp
echo
echo "info: starting deepspace filebackup on $timestamp"
echo
# check if configfile is there and readable
if [ -r $configfile ]; then
# read configfile
i=1
while read line; do
# check if first letter is a #
fletter=${line:0:1}
if [ -z "$line" ]; then
:
#echo "line $i is empty"
else
if [ $fletter == "#" ]; then
:
#echo "line $i a comment"
else
if [[ $line != *"@"*":"*";"* ]]; then
echo "error: line $i is not correct formated"
else
echo "info: reading config (line $i)"
userindex=`expr index "$line" @`
let userindex--
user=${line:0:$userindex}
#echo "user: $user"
hostindex=`expr index "$line" :`
let hostindex--
let userindex++
host=${line:$userindex:$(($hostindex-$userindex))}
#echo "host: $host"
passindex=`expr index "$line" ";"`
share=${line:$(($hostindex+1)):$(($passindex-$hostindex-2))}
#echo "share: $share"
pass=${line:$passindex}
#echo "password: $pass"
# check for mountpoint
if [ -d $mountpath/$i ]; then
echo "info: $mountpath/$i already exists"
else
mkdir -p $mountpath/$i
fi
echo "info: mounting $host$share to $mountpath/$i"
mount -t cifs -o username=$user,password=$pass //$host$share $mountpath/$i
# do backup
echo "info: creating destination folders"
mkdir -p $backuppath/$timestamp/$host$share/
echo "info: starting rsync job"
rsync -r $mountpath/$i/* $backuppath/$timestamp/$host$share/
# unmounting share
echo "info: unmounting $host$share"
umount $mountpath/$i
echo "info: backup done, please check if it's really there"
echo
fi
fi
fi
let i++
done < $configfile
else
echo "error: no configfile found"
exit 1
fi
exit 0

View File

@ -0,0 +1,15 @@
b8:ac:6f:86:7d:49 dooku
00:22:19:2f:a6:fb loadingapp
00:22:19:14:69:ea cluster1
00:22:19:14:6a:00 cluster2
00:22:19:14:37:cf cluster3
00:22:19:14:5f:bc cluster4
00:22:19:14:6a:2f lic
#devicecontrol
#mosaik1
00:22:19:14:6c:b5 mosaik2
00:22:19:14:69:52 sanchoplan
00:22:19:14:5f:77 stereovideowall
00:22:19:14:6a:d2 stereovideofloor
00:22:19:11:e3:08 video
00:14:c2:5a:28:3e testmachine

62
clonebackup/start_backup.sh Executable file
View File

@ -0,0 +1,62 @@
#!/bin/bash
#hosts="cluster1 cluster2 cluster3 cluster4 lic sanchoplan stereovideowall stereovideofloor video loadingapp"
hosts="testmachine"
pxeconfdir="/var/lib/tftpboot/pxelinux.cfg"
scriptpath="/srv/scripts"
# check for configfile
if [ -d $pxeconfdir ]; then
if [ -r $pxeconfdir/default ]; then
echo "default pxe config exists and is readable"
else
echo "default pxe config does not exist"
# create default pxe config
echo "creating config"
cp $scriptpath/tftpboot_default $pxeconfdir/default
fi
else
echo "there is no $pxeconfdir"
echo "are you sure you're running this script on your pxe server"
echo "exiting"
exit 1
fi
# cleaning up any previous mac address config files in pxeconfdir
echo "cleaning up previous mac address configurations in $pxeconfdir"
rm $pxeconfdir/00-* &> /dev/null
# starting actual backup process
set -- $hosts
for var in "$@"; do
echo "starting backup of $var"
# get mac for pxe config
macstring=$(cat $scriptpath/mac2hostname.lst | grep $var)
mac=${macstring:0:17}
correctmac="${mac//:/-}"
echo "mac of $var is $correctmac"
# create pxc config for $var
cp $scriptpath/tftpboot_mac $pxeconfdir/01-$correctmac
# remote reboot
echo "making the actual reboot of $var"
ssh -l Administrator $var shutdown -f -r -t 05
# sleep for 15 minutes
echo "sleeping for 10 minutes"
sleep 600
# remove temp pxe config for $var
echo "removing mac address configurations in $pxeconfdir"
rm $pxeconfdir/01-$correctmac
done
# end of script
echo "end of script, exiting"
exit 0

View File

@ -0,0 +1,5 @@
DEFAULT local
LABEL local
MENU LABEL Local ^HDD
LOCALBOOT 0

27
db/pg_backup.sh Executable file
View File

@ -0,0 +1,27 @@
#!/bin/bash
bakpath="/srv/backup"
count="5"
num=$count
cd $bakpath
while [ -a daily0.dump ]; do
if [ -a daily$num.dump ]; then
echo "moving daily$num.dump to daily$((num+1)).dump"
mv daily$num.dump daily$((num+1)).dump
fi
num=$((num-1))
done
echo "dumping postgresql dbs to a new daily0.dump"
sudo -u postgres pg_dumpall > daily0.dump
if [ -a daily$((count+1)).dump ]; then
rm daily$((count+1)).dump
echo "removing daily$((count+1)).dump"
fi
echo "done"
exit 0

10
db/restore_mysql_db.sh Executable file
View File

@ -0,0 +1,10 @@
#!/bin/bash
user=root
pass=xxxx
db=database
file=$1
mysql -u$user -p$pass -f $db < $file

16
df.conf.sample Normal file
View File

@ -0,0 +1,16 @@
## df monitoring jabber bot configfile
## here i suggest you put the name of the machine you running this script on
hostname="somemachine.example.com"
## jabber config
watchdogs="max@muster.com moriz@jabber.anotherdomain.com"
user="jabber-username"
pass="jabber-password"
server="jabber-server"
#port="5222" # uncomment if you want to use a specific port
## define disks you wanna check? (whitespace seperated)
disks="hda1 hda2 hdd1"
## here the disks thresholds
thresholds="80 90 95"

85
df.sh Normal file
View File

@ -0,0 +1,85 @@
#!/bin/bash
###################################################
## ##
## disk_free jabber monitoring bot ##
## Author: david@socialnerds.org ##
## v0.2 ##
## ##
###################################################
## timestamp for logfile
timestamp=$(date '+%d %B %Y %H:%M')
echo "info: starting df bot $timestamp"
## check if sendxmpp is installed
if [ $(aptitude search sendxmpp | awk '{print $1}') = "i" ]; then
echo "info: sendxmpp found"
else
if [ $(whoami) = "root" ]; then
apt-get install sendxmpp
else
echo "error: permission denied"
echo "info: install sendxmpp or run this scrip as superuser"
exit 1
fi
fi
## set and load configfile
if [ -z $1 ]; then
configfile="/etc/mobots/df.conf"
if [ -f $configfile ]; then
source $configfile
else
echo "error: no config file $configfile"
exit 1
fi
else
configfile=$1
if [ -f $configfile ]; then
source $configfile
else
echo "error: no config file $configfile"
exit 1
fi
fi
## check sendxmpp config
if [ -f ~/.sendxmpprc ]; then
echo "info: jabber config found in ~/.sendxmpprc"
else
if [ -z $port ]; then
port="5222"
else
echo "info: using port $port"
fi
echo "$user@$server:$port $pass" > ~/.sendxmpprc
chmod 600 ~/.sendxmpprc
echo "info: created sendxmpp config in ~/.sendxmpprc"
fi
## check disks
set -- $disks
i="1"
for var in "$@"
do
data=$(df -Ph | grep $var | sed -e 's/%//g' | awk '{print $5}')
datathreshold=$(echo $thresholds | awk '{print $'$i'}')
if [ $data -gt $datathreshold ]; then
echo "info: $var reached threshold with $data%, sending notification to $watchdogs"
echo "$hostname: $var is running out of space: $data%" | sendxmpp -r dfbot $watchdogs
fi
let i++
done
## exiting
echo "info: done"
exit 0

9
df_bot.conf.sample Normal file
View File

@ -0,0 +1,9 @@
# **** df_bot configfile ****
# here i suggest you put the name of the machine you running this script on
hostname="somemachine.example.com"
## define disks you wanna check? (whitespace seperated)
disks="hda1 hda2 hdd1"
## here the disks thresholds
thresholds="80 90 95"

120
df_bot.sh Normal file
View File

@ -0,0 +1,120 @@
#!/bin/bash
###################################################
## ##
## disk_free monitoring bot ##
## ##
###################################################
# **** in script config section ****
version="0.3_alpha"
author="david@socialnerds.org"
logwhat="df_bot"
# **** configfile section ****
disks="sda1"
thresholds="90"
bashlibpath="/home/david/Documents/code/bashlib"
# logging
loglevel="4"
log2syslog="1"
log2file="0"
#logfile="/var/log/mbots.log"
log2stdout="1"
# **** bash trap initialisation ****
trap bashtrap INT
# **** load bashlib ****
if [ -d $bashlibpath ]; then
source $bashlibpath/main
#source $bashlibpath/update
source $bashlibpath/logengine
log debug "preflight - bashlib loaded"
else
echo "ERROR: bashlib not found"
exit 1
fi
exit 0
## timestamp for logfile
#timestamp=$(date '+%d %B %Y %H:%M')
#echo "info: starting df bot $timestamp"
## check if sendxmpp is installed
#if [ $(aptitude search sendxmpp | awk '{print $1}') = "i" ]; then
# echo "info: sendxmpp found"
#else
# if [ $(whoami) = "root" ]; then
# apt-get install sendxmpp
# else
# echo "error: permission denied"
# echo "info: install sendxmpp or run this scrip as superuser"
# exit 1
# fi
#fi
## set and load configfile
#if [ -z $1 ]; then
# configfile="/etc/mobots/df.conf"
# if [ -f $configfile ]; then
# source $configfile
# else
# echo "error: no config file $configfile"
# exit 1
# fi
#else
# configfile=$1
# if [ -f $configfile ]; then
# source $configfile
# else
# echo "error: no config file $configfile"
# exit 1
# fi
#fi
## check sendxmpp config
#if [ -f ~/.sendxmpprc ]; then
# echo "info: jabber config found in ~/.sendxmpprc"
#else
#
# if [ -z $port ]; then
# port="5222"
# else
# echo "info: using port $port"
# fi
#
# echo "$user@$server:$port $pass" > ~/.sendxmpprc
# chmod 600 ~/.sendxmpprc
# echo "info: created sendxmpp config in ~/.sendxmpprc"
#fi
## check disks
set -- $disks
i="1"
for var in "$@"
do
data=$(df -Ph | grep $var | sed -e 's/%//g' | awk '{print $5}')
datathreshold=$(echo $thresholds | awk '{print $'$i'}')
if [ $data -gt $datathreshold ]; then
echo "info: $var reached threshold with $data%, sending notification to $watchdogs"
echo "$hostname: $var is running out of space: $data%" | sendxmpp -r dfbot $watchdogs
fi
let i++
done
## exiting
#echo "info: done"
exit 0
# **** end of script ****

10
flash_scrolllock.sh Executable file
View File

@ -0,0 +1,10 @@
#!/bin/bash
# Flash the Scroll Lock LED
while [ true ]; do
xset led named 'Scroll Lock'
sleep 0.3
xset -led named 'Scroll Lock'
sleep 0.3
done

33
ftpsftp/README.please Normal file
View File

@ -0,0 +1,33 @@
attention: the install procedure is broke at the moment..
## why are some variables defined in the configfile and some directly in the script?
the vars in the configfile are specific to your installation and can or should be changed. everything defined directly in the script should remain the same for every installation.
## features wanted
info option (or some sort of stats)
-- ftp user count
-- sftp user count
-- used disk space
-- used disk space by user
-- free disk space
-- free quota
-- quotamountpoint
## functions
quotacalc ... gives back the free megabytes on the storage
quotaconf ... sets the quota for existing user
isuserthere ... checks if user exists or asks to create it
amiroot ... checks if there are root privileges (ends scripts if not)
update ... pulls updates from ftpsftp git repository
version ... prints version information
usage ... prints usage message
add ... adding a new user
delete ... delete an existing user
contact me if you have any questions: david@socialnerds.org

View File

@ -0,0 +1,173 @@
#!/bin/bash
############################################
## ##
## FTP/sFTP Account Creation Script ##
## v0.2 ##
## Author: david@socialnerds.org ##
## ##
############################################
## script configuration section ##
accpath="/media/storage"
acchost="some.domain.org" # the dns name where your sever is reachable
sftpgroup="sftpusers" # this group must exist
trackrequester="yes" # switch to "no" if you do not want to track the requester
logging=1 # set this to 0 if you don't want any logging
logpath="/media/storage/logs" # there you want to create your logfile
logfile="accounts.log" # choose the logfile name here
jabberlog=1 # set this to 0 if you don't want jabber notifications
## following ist not necessary if jabberlog=0
jabberwatchdogs="admin@somedomain.org admin@someotherdomain.org"
jabberuser="jabber-account"
jabberserver="jabber-server"
jabberpass="jabber-account-password"
## am i root? ##
if [ "$(whoami)" != "root" ]; then
echo "only root can do this"
exit 1;
fi
## check for dependencys ##
# not yet implemented (sendxmpp, ssh, vsftpd, ..)
#clear
echo "" # just an empty line
echo "Welcome to the FTP/sFTP Account Creation Script (v0.2)"
## choose ftp or sftp
echo ""
echo "Which type of account you want to create? [sftp|ftp]"
read acctype
if [ $acctype = "sftp" ]; then
echo ""
else
if [ $acctype = "ftp" ]; then
echo ""
else
#clear
echo "I'm sorry, i need to break this up right now."
echo "It seams you can't understand some simple instructions.."
exit 1;
fi
fi
if [ -z $1 ]; then
needaccname="yes"
while [ $needaccname = "yes" ]; do
echo ""
echo "Enter Accountname:"
read accname
if [ -z $accname ]; then
echo "This field is mandatory."
else
needaccname="notanymore"
fi
done
else
accname=$1
fi
## quota
accquota="quota not yet implemented"
## requester
while [ $trackrequester = "yes" ]; do
echo ""
echo "Who orderd this account? (I'm tracking this for a greater good.)"
read accrequester
if [ -z "$accrequester" ]; then
echo "This field is mandatory."
else
trackrequester="notanymore"
fi
done
## set $accport
if [ $acctype = "sftp" ]; then
accport="22"
else
accport="21"
fi
## get timestamp
acctimestamp=$(date '+%dr%B %Y %H:%M')
## gen password (acpass)
accpass=$(pwgen -snc 10 1)
echo $accpass > pass.txt
accencpass=$(makepasswd --clearfrom=pass.txt --crypt-md5 |awk '{print $2}')
rm pass.txt
## create home, set its permissions and add the user to sftp/ftpgroup
if [ $acctype = "sftp" ]; then
mkdir -p $accpath/$acctype"_accounts"/$accname/data
# create the actual user (sftp)
useradd -d /data -M -U -s /usr/lib/sftp-server -p $accencpass $accname
chown -R $accname\: $accpath/$acctype"_accounts"/$accname/data
adduser $accname $sftpgroup
else
mkdir -p $accpath/$acctype"_accounts"/$accname
# create the actual user (ftp)
useradd -d $accpath/$acctype"_accounts"/$accname -M -U -s /bin/false -p $accencpass $accname
chown -R $accname\: $accpath/$acctype"_accounts"/$accname
echo $accname >> /etc/vsftpd.user_list
fi
## logging (log type, name, pass, quota, requester and timestamp)
if [ $logging = 1 ]; then
if [ -e $logpath/$logfile ]; then
cd $logpath
echo $acctype $accname $accpass $accquota $accrequester $acctimestamp >> $logfile
else
mkdir -p $logpath
cd $logpath
touch $logfile
echo "type name pass quota reguester timestamp" >> $logfile
echo $acctype $accname $accpass $accquota $accrequester $acctimestamp >> $logfile
fi
else
echo ""
fi
## jabber notification
if [ $jabberlog = 1 ]; then
echo "
This is your FTP/sFTP Server,
a "$acctype" account was just created.
Accountname:" $accname "
Quota:" $accquota "
Requester:" $accrequester | sendxmpp -r ftpcreation -u $jabberuser -j $jabberserver -p $jabberpass $jabberwatchdogs
else
echo ""
fi
## account data output
#clear
echo ""
echo "Account data"
echo ""
echo "Host:" $acchost
echo "Port:" $accport
echo "Username:" $accname
echo "Password:" $accpass
echo "Quota:" $accquota
echo "Directory:" $accpath/$acctype"_accounts"/$accname
echo "Requester:" $accrequester
echo ""
echo "Everything is done"
exit 0

View File

@ -0,0 +1,215 @@
#!/bin/bash
############################################
## ##
## FTP/sFTP Account Creation Script ##
## v0.3 ##
## Author: david@socialnerds.org ##
## ##
############################################
## script configuration section ##
accpath="/srv/storage"
quotamountpoint="/srv/storage"
acchost="some.domain.org" # the dns name where your sever is reachable
sftpgroup="sftpusers" # this group must exist
trackrequester="yes" # switch to "no" if you do not want to track the requester
logging=1 # set this to 0 if you don't want any logging
logpath="/media/storage/logs" # there you want to create your logfile
logfile="accounts.log" # choose the logfile name here
jabberlog=0 # set this to 0 if you don't want jabber notifications
maillog=0
## following ist not necessary if jabberlog=0
jabberwatchdogs="admin@somedomain.org admin@someotherdomain.org"
jabberuser="jabber-account"
jabberserver="jabber-server"
jabberpass="jabber-account-password"
## do not touch
version="v0.3"
## am i root? ##
if [ "$(whoami)" != "root" ]; then
echo "only root can do this"
exit 1;
fi
## check for dependencys ##
# not yet implemented (sendxmpp, ssh, vsftpd, ..)
#clear
echo "" # just an empty line
echo "Welcome to the FTP/sFTP Account Creation Script ($version)"
## choose ftp or sftp
echo ""
echo "Which type of account you want to create? [sftp|ftp]"
read acctype
if [ $acctype = "sftp" ]; then
:
else
if [ $acctype = "ftp" ]; then
:
else
#clear
echo "I'm sorry, i need to break this up right now."
echo "It seams you can't understand some simple instructions.."
exit 1;
fi
fi
if [ -z $1 ]; then
needaccname="yes"
while [ $needaccname = "yes" ]; do
echo ""
echo "Enter Accountname:"
read accname
if [ -z $accname ]; then
echo "This field is mandatory."
else
needaccname="notanymore"
fi
done
else
accname=$1
fi
## quota
ablocks=$(df | grep $quotamountpoint | awk '{print $2}')
gblocks=$(repquota $quotamountpoint | grep 000 | awk '{print $4}')
set -- $gblocks
quotacount=0
for var in "$@"
do
quotacount=$(($quotacount+$var))
done
gblocks=$quotacount
fblocks=$(($ablocks-$gblocks))
fsize=${fblocks:0:$((${#fblocks}-3))}
needaccquota="yes"
while [ $needaccquota = "yes" ]; do
echo ""
echo "Please specify how much diskspace this account should provide. (in Megabytes)"
echo "Maximum: $fsize"
read accquota
if [ -z "$accquota" ]; then
echo "This field is mandatory."
else
if [ $accquota -lt $fsize ]; then
needaccquota="notanymore"
else
echo ""
echo "Specified size too big or not a number. Try again."
fi
fi
done
## requester
while [ $trackrequester = "yes" ]; do
echo ""
echo "Who orderd this account? (I'm tracking this for a greater good.)"
read accrequester
if [ -z "$accrequester" ]; then
echo "This field is mandatory."
else
trackrequester="notanymore"
fi
done
## set $accport
if [ $acctype = "sftp" ]; then
accport="22"
else
accport="21"
fi
## get timestamp
acctimestamp=$(date '+%d.%m.%Y %H:%M')
## gen password (acpass)
accpass=$(pwgen -snc 10 1)
echo $accpass > pass.txt
accencpass=$(makepasswd --clearfrom=pass.txt --crypt-md5 |awk '{print $2}')
rm pass.txt
## create home, set its permissions and add the user to sftp/ftpgroup
if [ $acctype = "sftp" ]; then
mkdir -p $accpath/$acctype"_accounts"/$accname/data
# create the actual user (sftp)
useradd -d /data -M -U -s /usr/lib/sftp-server -p $accencpass $accname
chown -R $accname\: $accpath/$acctype"_accounts"/$accname/data
usermod -G $sftpgroup $accname
else
mkdir -p $accpath/$acctype"_accounts"/$accname
# create the actual user (ftp)
useradd -d $accpath/$acctype"_accounts"/$accname -M -U -s /bin/false -p $accencpass $accname
chown -R $accname\: $accpath/$acctype"_accounts"/$accname
echo $accname >> /etc/vsftpd.user_list
fi
## configure quota
setquota --all -u $accname $accquota"000" $accquota"000" 0 0
## logging (log type, name, pass, quota, requester and timestamp)
if [ $logging = 1 ]; then
if [ -e $logpath/$logfile ]; then
cd $logpath
echo $acctype $accname $accpass $accquota $accrequester $acctimestamp >> $logfile
else
mkdir -p $logpath
cd $logpath
touch $logfile
echo "type name pass quota reguester timestamp" >> $logfile
echo $acctype $accname $accpass $accquota $accrequester $acctimestamp >> $logfile
fi
else
echo ""
fi
## jabber notification
if [ $jabberlog = 1 ]; then
echo "
This is your FTP/sFTP Server,
a "$acctype" account was just created.
Accountname:" $accname "
Quota:" $accquota"MB" "
Requester:" $accrequester | sendxmpp -r ftpcreation -u $jabberuser -j $jabberserver -p $jabberpass $jabberwatchdogs
fi
## mail notification
if [ $maillog = 1 ]; then
echo "mail notification is not yet implemented"
fi
## account data output
#clear
echo ""
echo "Account data"
echo ""
echo "Host:" $acchost
echo "Port:" $accport
echo "Username:" $accname
echo "Password:" $accpass
echo "Quota:" $accquota"MB"
echo "Directory:" $accpath/$acctype"_accounts"/$accname
echo "Requester:" $accrequester
echo ""
echo "Everything is done"
exit 0

View File

@ -0,0 +1,510 @@
#!/bin/bash
#################################################
## ##
## FTPsFTP ##
## standalone ftp/sftp server solution ##
## ##
#################################################
# **** do not touch as long as you are not me ****
version="v0.4.1b"
author="david@socialnerds.org"
giturl="http://git.gitorious.org/aec/ftpsftp.git"
# **** usage message ****
usage()
{
cat << EOF
usage: ftpsftp options
OPTIONS:
-h show this message
-i install ftpsftp on this ubuntu box
-a <username> add a user
-d <username> delete a user (not yet implemented)
-r <username> reset password for user (not yet implemented)
-q <username> (re)set the quota for user ****new feature****
-u update ftpsftp (pull from git)
-v version information
EOF
}
# **** version message ****
version()
{
echo
echo "FTPsFTP - standalone ftp/sftp server solution"
echo
echo "vesion: $version"
echo "author: $author"
echo
}
# **** am i root? ****
amiroot()
{
if [ "$(whoami)" != "root" ]; then
echo
echo "sorry $USER, you need to gain root privileges to do this."
echo
exit 1;
fi
}
# **** installation routine ****
installation()
{
## am i root?
amiroot
## installing dependencies
echo "info: trying to install dependencies via apt"
apt-get update
apt-get install -y vsftpd ssh quota quotatool makepasswd pwgen git-core vim
## reading configuration from user (stdin)
echo "specify under which path the account home dirs should be stored (no tailing slash)"
read accpath
echo "specify the mointpoint of the device where your accounts are stored (needed for quota config)"
read quotamountpoint
echo "specify the fqdn of your host"
read acchost
echo "specify a system group for your sftp users [default: sftpusers]"
read sftpgroup
if [ -z $sftpgroup ]; then
sftpgroup="sftpusers"
fi
## creating needed directorys
echo "info: creating directorys"
mkdir -p /etc/ftpsftp
mkdir -p /var/log/ftpsftp
mkdir -p /opt
## creating configfiles and logfiles
echo "info: creating configuration and log files"
echo "$USER" > /etc/vsftpd.chroot_list
touch /etc/vsftpd.user_list
echo "type name pass quota reguester timestamp" > /var/log/ftpsftp/accounts.log
#touch /var/log/ftpsftp/system.log #not yet in use
echo '## ftpsftp configuration file ##
accpath="'$accpath'" # this should point to where your accounts should be located
quotamountpoint="'$quotamountpoint'" # mount point for quota configuration
acchost="'$acchost'" # the dns name where your sever is reachable
sftpgroup="'$sftpgroup'" # system group
trackrequester="1" # switch to 0 if you do not want to track the account requester
logging="1" # set this to 0 if you do not want any logging
mailnotification="0" # set this to 0 if you do not want any mail notifications (not yet implemented)
' > /etc/ftpsftp/ftpsftp.conf
## cloning master of ftpsftp git repo
echo "info: cloning files from git repository to /opt/ftpsftp"
cd /opt
git clone $giturl
## set symlink for script in /usr/local/bin
echo "info: creating symlink for script in /usr/local/bin"
cd /usr/local/bin
ln -s /opt/ftpsftp/ftpsftp.sh ftpsftp
## configure quota
echo "info: configuring quota in fstab for $quotamountpoint"
storageopt=$(cat /etc/fstab | grep $quotamountpoint | awk '{print $4}')
sed -i 's/'$storageopt'/'$storageopt',usrquota/' /etc/fstab
umount $quotamountpoint
mount -a
/etc/init.d/quota restart
## configure vsftp
cp /etc/vsftpd.conf /etc/vsftpd.conf_orig
#sed -i 's/#listen_ipv6=YES/listen_ipv6=YES/' /etc/vsftpd.conf
sed -i 's/#write_enable=YES/write_enable=YES/' /etc/vsftpd.conf
sed -i 's/#local_umask=022/local_umask=0007\nfile_open_mode=0770/' /etc/vsftpd.conf
sed -i 's/#chroot_local_user=YES/chroot_local_user=YES/' /etc/vsftpd.conf
sed -i 's/#chroot_list_enable=YES/chroot_list_enable=YES/' /etc/vsftpd.conf
sed -i 's/#chroot_list_file=\/etc\/vsftpd.chroot_list/chroot_list_file=\/etc\/vsftpd.chroot_list/' /etc/vsftpd.conf
sed -i 's/#ftpd_banner=Welcome to blah FTP service./ftpd_banner=Welcome to '$acchost'./' /etc/vsftpd.conf
echo "
## added by ftpsftp
userlist_enable=YES
userlist_deny=NO
userlist_file=/etc/vsftpd.user_list
" >> /etc/vsftpd.conf
/etc/init.d/vsftpd restart
## configure sshd
echo "info: configuring ssh server"
addgroup $sftpgroup
cp /etc/ssh/sshd_config /etc/ssh/sshd_config_orig
sed -i 's/Subsystem sftp \/usr\/lib\/openssh\/sftp-server/Subsystem sftp internal-sftp/' /etc/ssh/sshd_config
echo "
##### ssh configuration done by ftpsftp ############
AllowGroups admin $sftpgroup
Match group sftpusers
ChrootDirectory $accpath/sftp_accounts/%u
X11Forwarding no
AllowTcpForwarding no
ForceCommand internal-sftp
####################################################
" >> /etc/ssh/sshd_config
/etc/init.d/ssh restart
## adding shells
echo "
/bin/false
/usr/lib/sftp-server
" >> /etc/shells
echo "you can now delete this script."
echo "all you need is in /opt/ftpsftp, /etc/ftpsftp and /var/log/ftpsftp."
echo 'everything is set to create your first user. try "ftpsftp -a <username>"'
}
##### ftpsftp update #####
update()
{
## am i root?
amiroot
cd /opt/ftpsftp
git pull origin master
}
##### user creation #####
add()
{
## am i root?
amiroot
## set accname
accname=$1
## check if installed
## reading configfile
source /etc/ftpsftp/ftpsftp.conf
## choose ftp or sftp
echo "specify account type [sftp|ftp]"
read acctype
if [ $acctype = "sftp" ]; then
:
else
if [ $acctype = "ftp" ]; then
:
else
echo "i'm sorry, i need to break this up right now."
echo "it seams you can not understand some simple instructions."
exit 1
fi
fi
## quota
ablocks=$(df | grep $quotamountpoint | awk '{print $2}')
gblocks=$(repquota $quotamountpoint | grep 000 | awk '{print $4}')
set -- $gblocks
quotacount=0
for var in "$@"
do
quotacount=$(($quotacount+$var))
done
gblocks=$quotacount
fblocks=$(($ablocks-$gblocks))
fsize=${fblocks:0:$((${#fblocks}-3))}
needaccquota="yes"
while [ $needaccquota = "yes" ]; do
echo "please specify how much diskspace this account should provide. (in megabytes)"
echo "maximum: $fsize"
read accquota
if [ -z "$accquota" ]; then
echo "this field is mandatory."
else
if [ $accquota -lt $fsize ]; then
needaccquota="notanymore"
else
echo "specified size too big or not a number. try again."
fi
fi
done
## requester
while [ $trackrequester = "1" ]; do
echo "who orderd this account? (i'm tracking this for a greater good.)"
read accrequester
if [ -z "$accrequester" ]; then
echo "this field is mandatory."
else
trackrequester="notanymore"
fi
done
## set $accport
if [ $acctype = "sftp" ]; then
accport="22"
else
accport="21"
fi
## get timestamp
acctimestamp=$(date '+%d.%m.%Y %H:%M')
## gen password (accpass)
accpass=$(pwgen -snc 10 1)
echo $accpass > pass.txt
accencpass=$(makepasswd --clearfrom=pass.txt --crypt-md5 | awk '{print $2}')
rm pass.txt
## create home, set its permissions and add the user to sftp/ftpgroup
if [ $acctype = "sftp" ]; then
mkdir -p $accpath/$acctype"_accounts"/$accname/data
# create the actual user (sftp)
useradd -d /data -M -U -s /usr/lib/sftp-server -p $accencpass $accname
chown -R $accname\: $accpath/$acctype"_accounts"/$accname/data
usermod -G $sftpgroup $accname
else
mkdir -p $accpath/$acctype"_accounts"/$accname
# create the actual user (ftp)
useradd -d $accpath/$acctype"_accounts"/$accname -M -U -s /bin/false -p $accencpass $accname
chown -R $accname\: $accpath/$acctype"_accounts"/$accname
echo $accname >> /etc/vsftpd.user_list
fi
## configure quota
accquota=$((accquota/1000*1024))
setquota --all -u $accname $accquota"000" $accquota"000" 0 0
## trigger log
logging
## account data output
echo
echo "account data"
echo
echo "host:" $acchost
echo "port:" $accport
echo "username:" $accname
echo "password:" $accpass
echo "quota:" $accquota"mb"
echo "directory:" $accpath/$acctype"_accounts"/$accname
echo "requester:" $accrequester
echo
}
##### user deletion #####
delete()
{
## am i root?
amiroot
accname=$1
echo "feature not yet implemented"
}
##### password reset #####
reset()
{
## am i root?
amiroot
accname=$1
echo "feature not yet implemented"
}
resetquota()
{
accname=$1
## reading configfile
source /etc/ftpsftp/ftpsftp.conf
## quota calc
ablocks=$(df | grep $quotamountpoint | awk '{print $2}')
gblocks=$(repquota $quotamountpoint | grep 000 | awk '{print $4}')
set -- $gblocks
quotacount=0
for var in "$@"
do
quotacount=$(($quotacount+$var))
done
gblocks=$quotacount
fblocks=$(($ablocks-$gblocks))
fsize=${fblocks:0:$((${#fblocks}-3))}
needaccquota="yes"
while [ $needaccquota = "yes" ]; do
echo "please specify how much diskspace this account should provide. (in megabytes)"
echo "maximum: $fsize"
read accquota
if [ -z "$accquota" ]; then
echo "this field is mandatory."
else
if [ $accquota -lt $fsize ]; then
needaccquota="notanymore"
else
echo "specified size too big or not a number. try again."
fi
fi
done
## set quota
accquota=$((accquota/1000*1024))
setquota --all -u $accname $accquota"000" $accquota"000" 0 0
}
##### logging #####
logging()
{
if [ $logging = 1 ]; then
echo $acctype $accname $accpass $accquota $accrequester $acctimestamp >> /var/log/ftpsftp/accounts.log
fi
}
##### mail notification #####
#mailnotification()
#{
#
#if [ $maillog = 1 ]; then
# echo "mail notification is not yet implemented"
#fi
#
#}
##### processing options #####
while getopts "h,i,a:,d:,r:,q:,u,v" OPTION; do
case $OPTION in
h)
usage
exit 0
;;
i)
installation
exit 0
;;
a)
name=$OPTARG
run="yes"
while [ $run = "yes" ]; do
add $name
echo "do you want to create another user? (yes/no)"
read run
if [[ $run = "yes" ]] || [[ $run = "y" ]]; then
echo "specify account name"
read name
run="yes"
fi
done
exit 0
;;
d)
rmuser=$OPTARG
delete $rmuser
exit 0
;;
r)
rpuser=$OPTARG
reset $rpuser
exit 0
;;
q)
squser=$OPTARG
resetquota $squser
exit 0
;;
u)
update
exit 0
;;
v)
version
exit 0
;;
?)
usage
exit 1
;;
esac
done
## print usage message if no option is given
if [ -z $1 ]; then
usage
exit 1
fi
## end of script
exit 0

314
ftpsftp/ftpsftp.func Normal file
View File

@ -0,0 +1,314 @@
#!/bin/bash
#################################################
## ##
## FTPsFTP ##
## function definitions ##
## ##
#################################################
# **** usage message ****
usage()
{
echo "usage: ftpsftp options
OPTIONS:
-h show this message
-s show stats (not yet implemented)
-a <username> add a user
-d <username> delete a user
-r <username> reset password for user
-q <username> (re)set the quota for user
-u update ftpsftp (pull from git)
-v show version information
"
}
# **** version message ****
version()
{
echo "FTPsFTP - standalone ftp/sftp server solution"
echo
echo "vesion: $version"
echo "author: $author"
echo
}
# **** am i root? ****
# this is now in bashlib
#amiroot()
#{
#if [ "$(whoami)" != "root" ]; then
# echo
# echo "sorry $USER, you need to gain root privileges to do this."
# echo
# exit 1;
#fi
#}
# **** ftpsftp update ****
update()
{
# checking for root privileges
amiroot
# pull updates from ftpsftp git repository
cd /opt/ftpsftp
git pull origin master
log info "update - ftpsftp was updated (maybe)"
}
# ***** calculating free quota *****
quotacalc()
{
local ablocks=$(df | grep $quotamountpoint | awk '{print $2}')
local gblocks=$(repquota $quotamountpoint | grep 0 | awk '{print $4}')
set -- $gblocks
local quotacount=0
for var in "$@"; do
local quotacount=$(($quotacount+$var))
done
local gblocks=$quotacount
local fblocks=$(($ablocks-$gblocks))
local fsize=$((fblocks*1000/1024))
local fsize=${fsize:0:$((${#fsize}-3))}
# return result
echo $fsize
}
# **** set quota ****
quotaconf()
{
# checking for root privileges
amiroot
# checking if user exists
isuserthere $accname
# breaking up if user does not exist
if [ $? -eq "1" ]; then
echo "error: user does not exist."
exit 1
fi
# calculate free quota
local fsize=$(quotacalc)
local run="yes"
while [ $run = "yes" ]; do
echo "please specify quota for user $accname. (in megabytes)"
echo "maximum: $fsize"
read accquota
if [ -z "$accquota" ]; then
echo "this field is mandatory."
else
if [ $accquota -lt $fsize ]; then
local run="no"
else
echo "specified size too big or not a number. try again."
fi
fi
done
# set quota
accblockquota=$((accquota*1024))
setquota --all -u $accname $accblockquota $accblockquota 0 0
}
# **** check if user is already there or needs to be created ****
isuserthere()
{
id $accname &> /dev/null
if [ $? -eq "0" ]; then
return 0
else
return 1
fi
}
##### user creation #####
add()
{
# am i root?
amiroot
# checking if user already exists
isuserthere
# breaking up if user already exists
if [ $? -eq "0" ]; then
echo "error: user already exists."
exit 1
fi
# choose ftp or sftp
echo "specify account type [sftp|ftp]"
read acctype
if [ $acctype = "sftp" ]; then
:
else
if [ $acctype = "ftp" ]; then
:
else
echo "i'm sorry, i need to break this up right now."
echo "it seams you can not understand some simple instructions."
exit 1
fi
fi
# read requester if configfile option is 1
while [ $trackrequester = "1" ]; do
echo "who orderd this account? (i'm tracking this for a greater good.)"
read accrequester
if [ -z "$accrequester" ]; then
echo "this field is mandatory."
else
trackrequester="notanymore"
fi
done
# set accport
if [ $acctype = "sftp" ]; then
local accport="22"
else
local accport="21"
fi
# get timestamp
local acctimestamp=$(date '+%d.%m.%Y %H:%M')
# create home, set its permissions and add the user to sftp/ftpgroup
if [ $acctype = "sftp" ]; then
mkdir -p $accpath/$acctype"_accounts"/$accname/data
# create the actual user (sftp)
useradd -d /data -M -U -s /usr/lib/sftp-server $accname
chown -R $accname\: $accpath/$acctype"_accounts"/$accname/data
usermod -G $sftpgroup $accname
else
mkdir -p $accpath/$acctype"_accounts"/$accname
# create the actual user (ftp)
useradd -d $accpath/$acctype"_accounts"/$accname -M -U -s /bin/false $accname
chown -R $accname\: $accpath/$acctype"_accounts"/$accname
usermod -G $ftpgroup $accname
fi
# set password
local accpass=$(setpasswd)
# configure quota
quotaconf
# trigger logging
logging $acctype $accname $accpass $accquota $accrequester $acctimestamp
# print account data
echo
echo "account data"
echo
echo "host:" $acchost
echo "port:" $accport
echo "username:" $accname
echo "password:" $accpass
echo "quota:" $accquota"MB"
echo "directory:" $accpath/$acctype"_accounts"/$accname
echo "requester:" $accrequester
echo
}
# **** user deletion ****
delete()
{
# am i root?
amiroot
# checking if user exists
isuserthere
# breaking up if user does not exist
if [ $? -eq "1" ]; then
echo "error: user does not exist"
exit 1
fi
id -nG $accname | grep $sftpgroup &> /dev/null
if [ $? -eq "0" ]; then
deluser $accname &> /dev/null
rm -r $accpath/sftp_accounts/$accname
else
deluser $accname &> /dev/null
rm -r $accpath/ftp_accounts/$accname
fi
}
# **** generate password ****
setpasswd()
{
# checking if user exists
isuserthere
# breaking up if user does not exist
if [ $? -eq "1" ]; then
echo "error: user does not exist"
exit 1
fi
# generating password
local accpass=$(pwgen -snc 10 1)
echo $accpass > pass.txt
local accencpass=$(makepasswd --clearfrom=pass.txt --crypt-md5 | awk '{print $2}')
rm pass.txt
# setting the password
usermod -p $accencpass $accname
# returning unencrypded password
echo $accpass
}
# **** logging ****
logging()
{
if [ $logging -eq "1" ]; then
echo $@ >> $acclogfile
fi
}
# **** statistics ****
stats()
{
echo "feature not yet implemented"
}

116
ftpsftp/ftpsftp.sh Executable file
View File

@ -0,0 +1,116 @@
#!/bin/bash
#################################################
## ##
## FTPsFTP ##
## standalone ftp/sftp server solution ##
## ##
#################################################
# **** do not touch as long as you are not me ****
version="v0.5_beta"
author="david@socialnerds.org"
giturl="git://git.socialnerds.org/ftpsftp.git"
logwhat="ftpsftp"
log2stdout="1"
functionfile="/opt/ftpsftp/ftpsftp.func"
configfile="/etc/ftpsftp.conf"
# **** read function definitions and config file ****
if [ -r $functionfile ]; then
source $functionfile
else
echo "error: functionfile not found."
exit 1
fi
if [ -r $configfile ]; then
source $configfile
else
echo "error: configuration file not found."
exit 1
fi
# **** load bashlib ****
# need for some better routine to include bashlib
if [ -d $bashlibpath ]; then
source $bashlibpath/main
source $bashlibpath/logengine
log debug "preflight - logengine loaded"
else
echo "ERROR: bashlib not found"
exit 1
fi
# **** processing options ****
while getopts "h,s,a:,d:,r:,q:,u,v" OPTION; do
case $OPTION in
h)
usage
exit 0
;;
s)
stats
exit 0
;;
a)
accname=$OPTARG
run="yes"
while [ $run = "yes" ]; do
add
echo "do you want to create another user? (yes/no)"
read run
if [[ $run = "yes" ]] || [[ $run = "y" ]]; then
echo "specify account name"
read accname
run="yes"
fi
done
exit 0
;;
d)
accname=$OPTARG
delete
exit 0
;;
r)
accname=$OPTARG
accpass=$(setpasswd)
echo "the new password for user $accname is: $accpass"
exit 0
;;
q)
accname=$OPTARG
quotaconf
exit 0
;;
u)
update
exit 0
;;
v)
version
exit 0
;;
?)
usage
exit 1
;;
esac
done
# **** print usage message if no option is given ****
if [ -z $1 ]; then
usage
exit 1
fi
# **** end of script ****
exit 0

207
ftpsftp/install.sh Executable file
View File

@ -0,0 +1,207 @@
#!/bin/bash
#################################################
## ##
## FTPsFTP ##
## installation script ##
## ##
#################################################
# **** ftpsftp installation routine ****
# **** configuration section ****
giturl="http://git.gitorious.org/aec/ftpsftp.git"
acclogfile="/var/log/ftpsftp_accounts.log" #changed
logfile="/var/log/ftpsftp.log" #new
configfile="/etc/ftpsftp.conf" #changed
reporoot="/opt" #new
# **** am i root? ****
if [ "$(whoami)" != "root" ]; then
echo
echo "$USER, in order to do this you need to gain root privileges."
echo
exit 1;
fi
# **** uninstall ****
if [ -z $1 ]; then
:
elif [ $1 = "--uninstall" ]; then
# **** removing files ****
rm -r $reporoot/ftpsftp
rm $logfile
rm $acclogfile
rm $configfile
rm /etc/vsftpd.chroot_list
rm /usr/local/bin/ftpsftp
rm /etc/fstab
mv /etc/fstab_orig /etc/fstab
rm cp /etc/vsftpd.conf
mv /etc/vsftpd.conf_orig /etc/vsftpd.conf
rm /etc/vsftpd.group_list
rm cp /etc/pam.d/vsftpd
mv /etc/pam.d/vsftpd_orig /etc/pam.d/vsftpd
rm /etc/ssh/sshd_config
mv /etc/ssh/sshd_config_orig /etc/ssh/sshd_config
rm /etc/shells
mv /etc/shells_orig /etc/shells
# **** removing groups ****
#delgroup $sftpgroup
#delgroup $ftpgroup
echo "info: everything except the system groups and the packages installed with apt successfully removed"
fi
# **** installing dependencies ****
echo "info: trying to install dependencies via apt"
apt-get update
apt-get install -y vsftpd ssh quota quotatool makepasswd pwgen git-core vim
# **** reading configuration from user ****
echo "specify under which path the account home dirs should be stored (no tailing slash)"
read accpath
echo "specify the mointpoint of the device where your accounts are stored (needed for quota config)"
read quotamountpoint
echo "specify the fqdn of your host"
read acchost
echo "specify a system group for your sftp users [default: sftpusers]"
read sftpgroup
if [ -z $sftpgroup ]; then
sftpgroup="sftpusers"
fi
echo "specify a system group for your ftp users [default: ftpusers]"
read ftpgroup
if [ -z $ftpgroup ]; then
ftpgroup="ftpusers"
fi
# **** creating needed directorys ****
# just in case, they should be already there
echo "info: creating directorys"
mkdir -p /var/log
mkdir -p $reporoot
# **** creating configfiles and logfiles ****
echo "info: creating configuration and log files"
# creating chroot_list
echo "$USER" > /etc/vsftpd.chroot_list
# creating log files
echo "type name pass quota reguester timestamp" > $acclogfile
touch $logfile
# create ftpsftp configuration file (default: /etc/ftpsftp/ftpsftp.conf)
echo '## ftpsftp configuration file ##
accpath="'$accpath'" # this should point to where your accounts should be located
quotamountpoint="'$quotamountpoint'" # mount point for quota configuration
acchost="'$acchost'" # the dns name where your sever is reachable
sftpgroup="'$sftpgroup'" # system group
ftpgroup="'$ftpgroup'" # system group
trackrequester="1" # switch to 0 if you do not want to track the account requester
logging="1" # set this to 0 if you do not want any logging
' > $configfile
# **** cloning master branch of ftpsftp git repo ****
echo "info: cloning files from git repository to /opt/ftpsftp"
cd $reporoot
git clone $giturl
# **** set symlink for script in /usr/local/bin ****
echo "info: creating symlink for script in /usr/local/bin"
cd /usr/local/bin
ln -s $reporoot/ftpsftp/ftpsftp.sh ftpsftp
# **** configure quota ****
echo "info: configuring quota in fstab for $quotamountpoint"
cp /etc/fstab /etc/fstab_orig
cat /etc/fstab | grep -v $quotamountpoint > /etc/~fstab
storageopt=$(cat /etc/fstab | grep $quotamountpoint | awk '{print $4}')
sed -i 's/'$storageopt'/'$storageopt',usrquota/' /etc/fstab
cat /etc/fstab | grep $quotamountpoint >> /etc/~fstab
rm /etc/fstab && mv /etc/~fstab /etc/fstab
umount $quotamountpoint
mount -a
/etc/init.d/quota restart
# **** configure vsftp ****
cp /etc/vsftpd.conf /etc/vsftpd.conf_orig
#sed -i 's/#listen_ipv6=YES/listen_ipv6=YES/' /etc/vsftpd.conf
sed -i 's/#write_enable=YES/write_enable=YES/' /etc/vsftpd.conf
sed -i 's/#local_umask=022/local_umask=0007\nfile_open_mode=0770/' /etc/vsftpd.conf
sed -i 's/#chroot_local_user=YES/chroot_local_user=YES/' /etc/vsftpd.conf
sed -i 's/#chroot_list_enable=YES/chroot_list_enable=YES/' /etc/vsftpd.conf
sed -i 's/#chroot_list_file=\/etc\/vsftpd.chroot_list/chroot_list_file=\/etc\/vsftpd.chroot_list/' /etc/vsftpd.conf
sed -i 's/#ftpd_banner=Welcome to blah FTP service./ftpd_banner=Welcome to '$acchost'./' /etc/vsftpd.conf
# creating vsftpd.group_list (used by pam)
addgroup $ftpgroup
echo "
$ftpgroup
admin
" > /etc/vsftpd.group_list
# adding group list to pam.d
cp /etc/pam.d/vsftpd /etc/pam.d/vsftpd_orig
sed '2 a auth required pam_listfile.so item=group sense=allow file=/etc/vsftpd.group_list onerr=fail' /etc/pam.d/vsftpd > /etc/pam.d/vsftpd_new
rm /etc/pam.d/vsftpd && mv /etc/pam.d/vsftpd_new /etc/pam.d/vsftpd
# restarting ftp service
/etc/init.d/vsftpd restart
# **** configure sshd ****
echo "info: configuring ssh server"
addgroup $sftpgroup
cp /etc/ssh/sshd_config /etc/ssh/sshd_config_orig
sed -i 's/Subsystem sftp \/usr\/lib\/openssh\/sftp-server/Subsystem sftp internal-sftp/' /etc/ssh/sshd_config
echo "
##### ssh configuration done by ftpsftp ############
AllowGroups admin $sftpgroup
Match group sftpusers
ChrootDirectory $accpath/sftp_accounts/%u
X11Forwarding no
AllowTcpForwarding no
ForceCommand internal-sftp
" >> /etc/ssh/sshd_config
/etc/init.d/ssh restart
## adding shells
cp /etc/shells /etc/shells_orig
echo "
/bin/false
/usr/lib/sftp-server
" >> /etc/shells
echo "you can now delete this script."
echo "all you need is in $reporoot/ftpsftp, $configfile, $acclogfile and $logfile"
echo 'everything should be set to create your first user. try "ftpsftp -a <username>"'
echo
exit 0

53
hb.sh Normal file
View File

@ -0,0 +1,53 @@
#!/bin/bash
#\
# \
# \_ _ _ _ _ _ _ _ _ _ _ _ _
# #\
# # \
# heartbeat monitoring # \
# script # /
# # /
# _ _ _ _ _ _ _ _ _ _ _ _ _#/
# /
# /
#/
# **** config section ****
author="david@socialnerds.org"
version="0.2"
giturl="git://git.aec.at/mbots.git"
hostsfile="/etc/hosts"
log2stdout="1"
log2file="0"
#logfile=/var/log/mbots.log
log2syslog="1"
logwhat="mbots_hb"
# **** preflight ****
#searching for bashlib
if [ -z $BASHLIB ]; then
echo "ERROR: bashlib environment variable not set. terminating."
exit 1
else
$bashlibpath=$BASHLIB
fi
#load bashlib
if [ -d $bashlibpath ]; then
source $bashlibpath/main
source $bashlibpath/logengine
log debug "preflight - logengine loaded."
else
echo "ERROR: bashlib not found. terminating."
exit 1
fi
# **** end of script ****

1
heartbeat.lst.sample Normal file
View File

@ -0,0 +1 @@
# list of hostnames to monitor

147
heartbeat.sh Normal file
View File

@ -0,0 +1,147 @@
#!/bin/bash
#\
# \
# \_ _ _ _ _ _ _ _ _ _ _ _ _
# #\
# # \
# heartbeat monitoring # \
# script # /
# # /
# _ _ _ _ _ _ _ _ _ _ _ _ _#/
# /
# /
#/
# **** config section ****
#do not touch as long as you're not me
author="david@socialnerds.org"
version="0.1"
giturl="git://git.aec.at/mbots.git"
configfile="/etc/mbots/mbots.conf"
log2stdout="1"
logwhat="mbots_heartbeat"
file="/etc/mbots/heartbeat.lst"
# **** preflight ****
#read configfile
if [ -r $configfile ]; then
source $configfile
else
echo "ERROR: configfile not found. terminating."
exit 1
fi
#load bashlib
if [ -d $bashlibpath ]; then
source $bashlibpath/main
source $bashlibpath/logengine
log debug "preflight - logengine loaded"
else
echo "ERROR: bashlib not found. terminating."
exit 1
fi
#check environment
log info "**** starting heartbeat bot ****"
#set linecount to 1
linecount="1"
#read one line at a time
while read line; do
#find first letter to determine if line is empty or a comment
fletter=${line:0:1}
#check for first letter
if [ -z $fletter ]; then
#skip line it's empty
log debug "config - skipping line $linecount in $file: it's empty"
elif [ $fletter = "#" ]; then
#skip line it's a comment
log debug "config - skipping line $linecount in $file: it's a comment"
else
# getting hostname from heartbeat.lst
hostname=$(echo $line | awk '{print $1}')
log debug "checking $hostname"
#check ipv6
ipv6=$(dig $hostname AAAA +short | grep ":")
if [ -z "$ipv6" ]; then
log warning "no ipv6 record for $hostname"
log debug "checking /etc/hosts"
hosts=$(cat /etc/hosts | grep -iw $hostname | awk '{print $1}' | grep ":")
if [ -z $hosts ]; then
log warning "no ipv6 hosts entry found"
else
for var in $hosts; do
log info "pinging $hostname($var)"
ping6 -c 1 $var &> /dev/null
err=$?
if [ $err = "0" ]; then
log info "$hostname($var) is reachable"
else
log error "$hostname($var) is not reachable"
fi
done
fi
else
for var in $ipv6; do
log info "pinging $hostname($var)"
ping6 -c 1 $var &> /dev/null
err=$?
if [ $err = "0" ]; then
log info "$hostname($var) is reachable"
else
log error "$hostname($var) is not reachable"
fi
done
fi
#check ipv4
ipv4=$(dig $hostname A +noall +answer | grep -v ";" | grep -v "CNAME" | awk '{print $5}' | grep -v "^$")
if [ -z "$ipv4" ]; then
log warning "no ipv4 record for $hostname"
log debug "checking /etc/hosts"
hosts=$(cat /etc/hosts | grep -iw $hostname | awk '{print $1}' | grep ".")
if [ -z $hosts ]; then
log warning "no ipv4 hosts entry found"
else
for var in $hosts; do
log info "pinging $hostname($var)"
ping -c 1 $var &> /dev/null
err=$?
if [ $err = "0" ]; then
log info "$hostname($var) is reachable"
else
log error "$hostname($var) is not reachable"
fi
done
fi
else
for var in $ipv4; do
log info "pinging $hostname($var)"
ping -c 1 $var &> /dev/null
err=$?
if [ $err = "0" ]; then
log info "$hostname($var) is reachable"
else
log error "$hostname($var) is not reachable"
fi
done
fi
fi
let linecount++
done < $file
log debug "**** all checks done ****"
# **** end of script ****

123
htpasswd.py Executable file
View File

@ -0,0 +1,123 @@
#!/usr/bin/python
"""Replacement for htpasswd"""
# Original author: Eli Carter
import os
import sys
import random
from optparse import OptionParser
# We need a crypt module, but Windows doesn't have one by default. Try to find
# one, and tell the user if we can't.
try:
import crypt
except ImportError:
try:
import fcrypt as crypt
except ImportError:
sys.stderr.write("Cannot find a crypt module. "
"Possibly http://carey.geek.nz/code/python-fcrypt/\n")
sys.exit(1)
def salt():
"""Returns a string of 2 randome letters"""
letters = 'abcdefghijklmnopqrstuvwxyz' \
'ABCDEFGHIJKLMNOPQRSTUVWXYZ' \
'0123456789/.'
return random.choice(letters) + random.choice(letters)
class HtpasswdFile:
"""A class for manipulating htpasswd files."""
def __init__(self, filename, create=False):
self.entries = []
self.filename = filename
if not create:
if os.path.exists(self.filename):
self.load()
else:
raise Exception("%s does not exist" % self.filename)
def load(self):
"""Read the htpasswd file into memory."""
lines = open(self.filename, 'r').readlines()
self.entries = []
for line in lines:
username, pwhash = line.split(':')
entry = [username, pwhash.rstrip()]
self.entries.append(entry)
def save(self):
"""Write the htpasswd file to disk"""
open(self.filename, 'w').writelines(["%s:%s\n" % (entry[0], entry[1])
for entry in self.entries])
def update(self, username, password):
"""Replace the entry for the given user, or add it if new."""
pwhash = crypt.crypt(password, salt())
matching_entries = [entry for entry in self.entries
if entry[0] == username]
if matching_entries:
matching_entries[0][1] = pwhash
else:
self.entries.append([username, pwhash])
def delete(self, username):
"""Remove the entry for the given user."""
self.entries = [entry for entry in self.entries
if entry[0] != username]
def main():
"""%prog [-c] -b filename username password
Create or update an htpasswd file"""
# For now, we only care about the use cases that affect tests/functional.py
parser = OptionParser(usage=main.__doc__)
parser.add_option('-b', action='store_true', dest='batch', default=False,
help='Batch mode; password is passed on the command line IN THE CLEAR.'
)
parser.add_option('-c', action='store_true', dest='create', default=False,
help='Create a new htpasswd file, overwriting any existing file.')
parser.add_option('-D', action='store_true', dest='delete_user',
default=False, help='Remove the given user from the password file.')
options, args = parser.parse_args()
def syntax_error(msg):
"""Utility function for displaying fatal error messages with usage
help.
"""
sys.stderr.write("Syntax error: " + msg)
sys.stderr.write(parser.get_usage())
sys.exit(1)
if not options.batch:
syntax_error("Only batch mode is supported\n")
# Non-option arguments
if len(args) < 2:
syntax_error("Insufficient number of arguments.\n")
filename, username = args[:2]
if options.delete_user:
if len(args) != 2:
syntax_error("Incorrect number of arguments.\n")
password = None
else:
if len(args) != 3:
syntax_error("Incorrect number of arguments.\n")
password = args[2]
passwdfile = HtpasswdFile(filename, create=options.create)
if options.delete_user:
passwdfile.delete(username)
else:
passwdfile.update(username, password)
passwdfile.save()
if __name__ == '__main__':
main()

30
htpasswd.sh Executable file
View File

@ -0,0 +1,30 @@
#!/bin/bash
function usage {
echo "./htpasswd.sh <username> <file>"
}
if [ $1 ]; then
USER=$1
else
USER=$(whoami)
fi
SUCCESS=1
while [ $SUCCESS -ne 0 ]; do
PASSWD=$(openssl passwd -apr1)
if [ $? -eq 0 ]; then
SUCCESS=0
fi
done
if [ $2 ]; then
FILE=$2
if [ $FILE ]; then
echo "$USER:$PASSWD" >> $FILE
fi
else
echo "$USER:$PASSWD"
fi
exit 0

53
install_moka.sh Executable file
View File

@ -0,0 +1,53 @@
#!/bin/bash
# moka icon theme install script
tempdir="/tmp/moka"
baseurl="https://github.com/snwh"
repolist="moka-icon-theme
moka-icon-theme-extras
moka-icon-theme-symbolic
moka-icon-theme-dark
moka-icon-theme-blue"
if [ $(whoami) != "root" ]; then
echo "you are not running this script with root privileges."
echo -e "installing moka-icon-theme only for $(whoami). continue? (y/n) \c"
read choice
if [ $choice != "y" ] && [ $choice != "Y" ]; then
exit 1
fi
else
echo "you are running this script with root privileges."
echo -e "installing moka-icon-theme systemwide. continue? (y/n) \c"
read choice
if [ $choice != "y" ] && [ $choice != "Y" ]; then
exit 1
fi
fi
if [ -d $tempdir ]; then
rm -r $tempdir
fi
echo "cloning repositories to $tempdir"
for theme in $repolist; do
mkdir $tempdir; cd $tempdir
git clone $baseurl/$theme".git"
if [ $? -ne 0 ]; then
echo "you might not have git installed."
exit 1
fi
if [ $(whoami) != "root" ]; then
cp -r $tempdir/$theme/Mok* $HOME/.icons
else
cp -r $tempdir/$theme/Mok* /usr/share/icons
fi
cd -
done
echo "cleaning up"
rm -r $tempdir
echo "everything done"
exit 0

43
install_yaourt.sh Executable file
View File

@ -0,0 +1,43 @@
#!/bin/bash
# archlinux yaourt installer
baselink="https://aur.archlinux.org/packages"
packages="package-query yaourt"
#uncomment following for passing the packages as option
#if [ -z $1 ]; then
# echo "usage: ./install_yaourt.sh <list of packages>"
# exit 1
#fi
#packages="$*"
tmpfolder="getyaourt"
sudo pacman -Syu
sudo pacman -S fakeroot binutils gcc make patch pkg-config wget git autoconf
for package in $packages; do
if [ -d /tmp/$tmpfolder ]; then
rm -rf /tmp/$tmpfolder #use sudo on a multiuser system
fi
mkdir /tmp/$tmpfolder
link=$(curl -s "$baselink/$package" | grep "Download tarball" | sed 's/"/\ /g' | awk '{print $3}')
cd /tmp/$tmpfolder
wget "https://aur.archlinux.org$link" && tar xzf *
cd $package; makepkg -s
if [ $? -eq 0 ]; then
sudo pacman -U *.xz
else
echo "error: could not source PKGBUILD"
fi
cd - > /dev/null
rm -rf /tmp/$tmpfolder
done
echo "info: everything done"

9
jekyll.sh Executable file
View File

@ -0,0 +1,9 @@
#!/bin/bash
export JEKYLL_VERSION=4.2.0
docker run --rm \
--volume="$PWD:/srv/jekyll" \
--volume="$HOME/Public/docs:/srv/docs" \
-p 127.0.0.1:4000:4000/tcp \
-it jekyll/jekyll:$JEKYLL_VERSION \
jekyll $@

49
journal.sh Normal file
View File

@ -0,0 +1,49 @@
#!/bin/bash
#
# journal script for keeping
# track of what i do and think
#
# it makes sence you add a bash alias like this to your ~/.bashrc
# alias='/path/to/journal.sh /path/to/outputfile.txt'
# do that and you can use journal as follows:
# usage: journal
# journal read
# journal edit
#check if output file is given as first option
if [ -z $1 ]; then
outputfile=journal.txt
else
outputfile=$1
fi
if [ -z $2 ]; then
:
else
if [ $2 = "read" ]; then
less $outputfile
exit $?
elif [ $2 = "edit" ]; then
vim $outputfile
exit $?
fi
fi
#generating timestamp
timestamp=$(date '+%d.%m.%Y %H:%M')
#read journal entry from stdin
echo "enter oneliner into journal:"; read input
#writing to outputfile
echo "**** $timestamp ****" >> $outputfile
echo $input >> $outputfile
echo "" >> $outputfile
# **** end of script ****

1
kvm-tools/README.md Normal file
View File

@ -0,0 +1 @@
#this repository is discontinued.

41
kvm-tools/README.please Normal file
View File

@ -0,0 +1,41 @@
# **** kvm-tools readme file ****
what we have here is a litte tool to backup your kvm/libvirt virtual machines really convenient! check it out!
this readme was first released with kvm-tools.sh v0.1rc on the 21st of april 2011, that's why i call it judgementday release.
# **** installation ****
# here on a ubuntu machine, but kvm-tools should
# run perfectly on all unix based operating systems
# as long as there is a bash and libvirt
run:
sudo apt-get install git-core (if you do not have git installed already)
cd /opt
sudo git clone git://git.socialnerds.org/kvm-tools.git
sudo git clone git://git.socialnerds.org/bashlib.git
rename the configfile sample to kvm-tools.conf
move it to /etc/kvm-tools.conf
and change its content to meet your needs
after configuration run:
cd /opt/kvm-tools
sudo ./kvm-tools.sh -f
finished!
for usage help type:
"kvm-tools -h" or just "kvm-tools"
# **** in progress ****
future features
- browsevdisk (mounting a virtual disk (img, qcow2) in the hosts filesystem)
hints
- a domain uuid should just exist once in the configuration folder
- only files with .xml will be read in the configpath

View File

@ -0,0 +1,44 @@
#!/bin/bash
#
# mount script for qcow2 images
# v0.1
#
# read imagename
if [ -z $1 ]; then
echo 'usage: "browseqcow2 <image.qcow2>"'
exit 1
fi
imagename=$1
# im i root
if [ $(whoami) != "root" ]; then
echo "only root can do this"
exit 1
fi
# run unmount
if [[ $1 = "--unmount" || $1 = "-u" || $1 = "--umount" ]]; then
umount /mnt/
qemu-nbd --disconnect /dev/nbd0
echo "image unmounted"
echo
exit 0
fi
# load kernel module
modprobe nbd max_part=8
# gen blockdevice
qemu-nbd --connect=/dev/nbd0 $imagename
# make the actual mount
sleep 2
mount /dev/nbd0p1 /mnt/
echo "$imagename is mounted in /mnt"
echo 'run "browseqcow2.sh --unmount" when ready'
echo

View File

@ -0,0 +1,58 @@
#!/bin/bash
if [ $(whoami) = "root" ]; then
:
else
echo "only root can do this"
exit 1
fi
echo "hostname?"
read hostname
echo "username?"
read username
echo "architecture? [amd64]"
read arch
echo "disksize? [8]"
read disksize
if [ -z $disksize ]; then
disksize=8192
else
disksize=$((disksize*1024))
fi
if [ -z $arch ]; then
arch="amd64"
fi
clear
echo
echo "a virtual machine with following details will be created in $(pwd)"
echo
echo "hostname: $hostname"
echo "os: lucid lynx"
echo "architecture: $arch"
echo "disksize: $disksize"
echo "password: password"
echo "proceed? [yes]"
read proceed
if [ -z $proceed ]; then
proceed="yes"
fi
if [ $proceed = "yes" ]; then
:
else
exit 1
fi
ubuntu-vm-builder kvm lucid --arch "$arch" --mem '512' --rootsize "$disksize" --swapsize '1024' --kernel-flavour 'virtual' --hostname "$hostname" --domain 'socialnerds.org' --mirror 'http://roxy.socialnerds.org/ubuntu' --components 'main,restricted,universe,multiverse' --addpkg "ssh" --name 'creator' --user "$username" --pass 'password'
echo
echo "creation finished"
exit 0

View File

@ -0,0 +1,16 @@
#!/bin/bash
if [ -z $1 ]; then
# reading the imagename
echo "what name should it have?"
read name
else
name=$1
fi
# generating the actual image
qemu-img create -f qcow2 $name.qcow2 16G
exit 0

View File

@ -0,0 +1,14 @@
#!/bin/bash
# generating new ids for a vm
newuuid=$(uuidgen)
newmac=$(MACADDR="52:54:$(dd if=/dev/urandom count=1 2>/dev/null | md5sum | sed 's/^\(..\)\(..\)\(..\)\(..\).*$/\1:\2:\3:\4/')"; echo $MACADDR)
# printing new ids
#clear
echo
echo "UUID: $newuuid"
echo "MAC: $newmac"
echo
exit 0

66
kvm-tools/firstboot.sh Executable file
View File

@ -0,0 +1,66 @@
#!/bin/bash
#######################################
## ##
## firstboot script ##
## kvm-tools ##
## ##
#######################################
# **** configuration section ****
sshgroup="sshusers"
user=$(cat /etc/passwd | grep 1000)
user=${user:0:$(($(echo `expr index "$user" :`)-1))}
# **** installing fortunes-ubuntu-server ****
apt-get update
apt-get install -y fortunes-ubuntu-server
# **** motd ****
echo 'if you want to have here something like this:
___.
\_ |__ _______ ___
| __ \ / _ \ \/ /
| \_\ ( <_> > <
|___ /\____/__/\_ \
\/ \/.socialnerds.org
socialnerds mail server
go to http://www.network-science.de/ascii/ and modify /etc/motd.tail
' > /etc/motd.tail
rm /etc/update-motd.d/10-help-text
rm /etc/update-motd.d/00-header
echo '#!/bin/bash' > /etc/update-motd.d/00-header
echo 'echo "Running Kernel: $(uname -r)"' >> /etc/update-motd.d/00-header
chmod +x /etc/update-motd.d/00-header
# **** ssh server config ****
echo "
__.-._
'-._'7'
/'.-c
| /T
_)_/LI
this machine is
protected by a
master of the force!
" > /etc/issue.net
sed -i 's/#Banner/Banner/' /etc/ssh/sshd_config
echo "" >> /etc/ssh/sshd_config
echo "# Restrictions added by firstboot.sh" >> /etc/ssh/sshd_config
echo "AllowGroups $sshgroup" >> /etc/ssh/sshd_config
echo "" >> /etc/ssh/sshd_config
addgroup $sshgroup
adduser $user $sshgroup
# **** end of script ****
exit 0

View File

@ -0,0 +1,24 @@
# **** kvm-tools sample config file ****
# this file should be renamed to kvm-tools.conf and moved to /etc
# locations (do not use tailing slashes)
repopath="/opt/kvm-tools" # path to the local kvm-tools git repo
configpath="/etc/libvirt/qemu" # path to the xml config files
imagepath="/path/to/images" # virtual disks location (just for vm creation)
backuppath="/path/to/backup" # backup destination
# bashlib
bashlibpath="/opt/bashlib" # bashlib location
# logging
loglevel="4"
log2stdout="1"
log2syslog="1"
log2file="1"
logfile="/var/log/kvm-tools.log"
# server deployment (ubuntu)
defaultdomain="aec.at"
defaultmirror="http://updater.aec.at/ubuntu"
recpackages="ssh bash-completion acpid unattended-upgrades nload htop tshark nmap aptitude ncdu parted vim logrotate apparmor-profiles apparmor-utils"
optpackages="screen nano dnsutils locate dialog pwgen git-core iftop mtr lft zsh"

638
kvm-tools/kvm-tools.func Normal file
View File

@ -0,0 +1,638 @@
#!/bin/bash
#######################################
## ##
## function definitions ##
## kvm-tools ##
## ##
#######################################
# **** usage message ****
# this will print the usage message
usage()
{
echo "usage: kvm-tools options <args>
OPTIONS:
-c <vmname> create guest
-e <vmname> edit guest
-a <vmname> add virtual disk to guest
-b <vmname|all> backup guest(s)
-h show this message
-v show version information
-i generate new id's
-f run environment check/fix
-u update kvm-tools (pull from git)
"
}
# **** version message ****
# this will print the version message
version()
{
echo
echo "kvm-tools"
echo
echo "vesion: $version"
echo "author: $author"
echo
log debug "version - version information printed"
}
# **** get image path(s) ****
# with parse the image path(s) from xml
getimgpath()
{
local raw=$(virsh dumpxml $1 | grep "file=" | grep -v "/dev/" | tr -d "<'>")
for item in $raw; do
if [ $item = "source" ]; then
:
else
echo ${item:5:$(($(echo `expr length "$item"`)-6))}
fi
done
}
# **** get xml path ****
# will search for matching uuid in $configpath and defines global variable $xmlpath
getxmlpath()
{
local list=$(ls $configpath | grep xml | grep -v "~")
local uuid=$(virsh domuuid $1)
local i=0
for var in $list; do
if [ -w $configpath/$var ]; then
local raw=$(cat $configpath/$var | grep uuid)
local uuidfromfile=${raw:8:36}
if [ $uuidfromfile = $uuid ]; then
xmlpath="$configpath/$var"
let i++
fi
else
log error 'getxmlpath - some of the xml configuration files are not writeable, run "kvm-tools -f" to fix this'
exit 1
fi
done
if [ $i = "1" ]; then
:
return 0
elif [ $i = "0" ]; then
log error "getxmlpath - xml file for $1 could not be determined in $configpath"
exit 1
elif [ $i -gt "1" ]; then
log error "getxmlpath - there is more than one file with matching uuid in $configpath"
exit 1
fi
}
# **** dialog window creation ****
# creates the dialog windows
graph()
{
local bgtitle="kvm-tools $version | $1"
if [ $2 = "--inputbox" ]; then
local size="7 80"
elif [ $2 = "--yesno" ]; then
local size="20 80"
elif [ $2 = "--fselect" ]; then
local size="12 80"
else
local size="20 80 14"
fi
dialog --backtitle "$bgtitle" --no-cancel "$2" "$3" $size $4 2> /tmp/dialog
local returncode=$?
clear
dialogresult=$(cat /tmp/dialog)
rm /tmp/dialog
return $returncode
}
# **** backup ****
# the virtual disk image and the xml config file
# will be saved to the backuppath
backup()
{
# am i root?
amiroot
# creat local variable with given machines (comma seperated list)
local list=$1
# creat local variables with all running/all shutoff machines (whitespace seperated)
local running=$(virsh list --all | grep "running" | awk '{print $2}')
local shutoff=$(virsh list --all | grep "shut off" | awk '{print $2}')
# check for given option "all"
if [ $list = "all" ]; then
# if "all" was given fill the list with all machines
list="$running $shutoff"
else
# otherwise just change the commas to whitespaces in the list
local list=${list//,/ }
fi
# getting a short timestamp like this 20110423
#local timestamp=$(gettimestamp short)
# $var will be the machine name
for var in $list; do
log info "backup - starting backup of $var"
# BACKUP XML file to backuppath
virsh dumpxml $var > $backuppath/$var.xml
log debug "backup - backing up xml file for $var"
# SUSPEND machine if running
local run=0
if [ $(echo $shutoff | grep -c $var) = "0" ]; then
log debug "backup - suspending $var"
virsh suspend $var &> /dev/null
local run=$?
fi
# check if suspend was successfull (if not.. skip)
if [ $run = 0 ]; then
# check for more than one image file
for item in $(getimgpath $var); do
# CEATE HASH for image diff
log debug "backup - creating sha1 hash of $item"
local sum=$(sha1sum $item | awk '{print $1}')
# get new filename
local newfile=${item##/*/}
#local ending=${item:$(echo `expr index "$item" .`)}
# BACKUP IMAGE file to backuppath
log debug "backup - backing up $item"
cp $item $backuppath/$newfile
# RESUME machine if paused
if [ $(echo $shutoff | grep -c $var) = "0" ]; then
log debug "backup - resuming $var"
virsh resume $var &> /dev/null
fi
# CHECK if HASH matches
log debug "backup - creating sha1 hash of $backuppath/$newfile"
if [ $sum = $(sha1sum $backuppath/$newfile | awk '{print $1}') ]; then
log debug "backup - hash for $newfile was successfully checked"
log info "backup - $var successfully backuped"
else
log error "backup - hash for $newfile does not match"
fi
done
else
log error "backup - could not suspend $var, skipping backup of $var"
fi
done
}
# **** edit vm config (xml) ****
# opens vim with xml file for given guest
edit()
{
# i shouldn't be root
amiroot not
# get the xml filepath for $1
getxmlpath $1
# create sum for diff
sha1sum $xmlpath > /tmp/checksum
vi $xmlpath
sha1sum -c --status /tmp/checksum
if [ "$?" = "0" ]; then
log debug "edit - $USER did not change xml configuration for $1"
else
virsh define $xmlpath &> /dev/null
log info "edit - $USER changed xml configuration for $1"
fi
rm /tmp/checksum
}
# **** fix stuff :) ****
# environment check, fixes stuff :)
fix()
{
# am i root?
amiroot
# install missing dependencies
log debug "fix - installing missing dependencies"
apt-get update
apt-get install -y dialog pwgen libvirt-bin python-vm-builder libxml-xpath-perl
# reseting file permissions in $configpath
chgrp -R libvirtd $configpath
chmod -R 775 $configpath
log debug "fix - reseted permissions in $configpath"
# fixing perms in $imagepath
chmod -R 775 $imagepath
chgrp -R libvirtd $imagepath
log debug "fix - reseted permission in $imagepath"
if [ -r $logfile ]; then
chmod 775 $logfile
chgrp libvirtd $logfile
log debug "fix - reseted permission for $logfile"
else
touch $logfile
chmod 775 $logfile
chgrp libvirtd $logfile
log debug "fix - created $logfile and set permissions"
fi
# adding kvm-tools to /usr/bin (symlink)
if [ -r /usr/bin/kvm-tools ]; then
:
else
ln -s $repopath/kvm-tools.sh /usr/bin/kvm-tools
log debug "fix - created a symlink for kvm-tools in /usr/bin"
fi
log info "fix - environment fix for kvm-tools successfully ran"
return 0
}
#browseqcow()
#{
# # read imagename
# if [ -z $1 ]; then
# echo 'usage: "browseqcow2 </path/to/image.qcow2>"'
# exit 1
# fi
#
# imagename=$1
#
#
# # im i root
# amiroot
#
# # run unmount
# if [[ $1 = "--unmount" || $1 = "-u" || $1 = "--umount" ]]; then
# umount /mnt/
# qemu-nbd --disconnect /dev/nbd0
# echo "image unmounted"
# echo
# exit 0
# fi
#
# # load kernel module
# modprobe nbd max_part=8
#
# # gen blockdevice
# qemu-nbd --connect=/dev/nbd0 $imagename
#
# # make the actual mount
# sleep 2
# mount /dev/nbd0p1 /mnt/
#
# echo "$imagename is mounted in /mnt"
# echo 'run "browseqcow2.sh --unmount" when ready'
# echo
#}
# **** add image ****
# attaches new created virtual disk to given guest
addimage()
{
# no need for root privileges
amiroot not
# virtual machine name (passed)
local hostname=$1
# genqcow2
genqcow $hostname
# xmlpath for $hostname
getxmlpath $hostname
local targets="vdb vdc vdd vde vdf vdg vdh vdi vdj"
for var in $targets; do
virsh dumpxml $hostname | grep $var
if [ $? = 1 ]; then
local where=$(sed -n '/\/disk/=' $xmlpath)
for item in $where; do
local nr=$item
done
sed ''$nr' a <disk type="file" device="disk"> <driver name="qemu" type="qcow2" /> <source file="'$imagepath/$imagename'" /> <target dev="'$var'" bus="virtio" /> </disk>' $xmlpath > $xmlpath"_new"
rm $xmlpath && mv $xmlpath"_new" $xmlpath
virsh define $xmlpath
log info "addimage - $var was added to $hostname"
chmod 775 $xmlpath
chgrp libvirtd $xmlpath
exit 0
else
log error "addimage - $var already exists for $hostname"
fi
done
}
# **** does image exist? ****
# checks if images exists and gives back errorcode(0 if its there, 1 of not)
imgexisting()
{
# imgexisting needs global vars: $imagepath
# usage: imgexisting hostname imagename
# passed args
local hostname=$1
local imagename=$2
virsh dumpxml $hostname | grep $imagename
local inxml=$?
ls $imagepath | grep $imagename
local inpath=$?
if [ $inpath = 0 ]; then
log info "imgexisting - $imagename exists in $imagepath"
return 0
elif [ $inxml = 0 ]; then
log info "imgexisting - $imagename exists in the xml of $hostname"
return 0
else
log info "imgexisting - $imagename is not existing"
return 1
fi
}
# **** generate qcow2 image ****
# creates a qcow2 image in the $imagepath
genqcow()
{
local bgmessage="virtual disk creation"
local hostname=$1
# imagename
local exists=0
while [ $exists = 0 ]; do
graph "$bgmessage" --inputbox "imagename?" $hostname"_storage.qcow2"
imagename="$dialogresult" #global var
imgexisting $hostname $imagename
local exists=$?
done
# imagesize
graph "$bgmessage" --menu "imagesize?" "4 GB 8 GB 16 GB 32 GB 64 GB 128 GB"
local imagesize="$dialogresult"
# generating the actual image
qemu-img create -f qcow2 $imagepath/$imagename $imagesize"G"
log info "genqcow - image with $imagesize"GB" created: $imagepath/$imagename"
chgrp libvirtd $imagepath/$imagename
chmod 775 $imagepath/$imagename
}
# **** generates new id's ****
# prints new ids to the logengine
newids()
{
# you shouldn't be root
amiroot not
# generating new ids for a vm
local newuuid=$(uuidgen)
local newmac=$(MACADDR="52:54:$(dd if=/dev/urandom count=1 2>/dev/null | md5sum | sed 's/^\(..\)\(..\)\(..\)\(..\).*$/\1:\2:\3:\4/')"; echo $MACADDR)
# printing new ids
log info "newids - $USER generated new id's"
echo
echo "UUID: $newuuid"
echo "MAC: $newmac"
echo
}
# **** create virtual ubuntu server ****
# this will start the wizard for creating a new virtual machine
mkjeos()
{
# config section
local bgmessage="server deployment"
local hostname=$1
# am i root?
amiroot
# configuration wizard
proceed=1
while [ $proceed != "0" ]; do
# hosname
graph "$bgmessage" --inputbox "hostname?" $hostname
local hostname="$dialogresult"
# domain
graph "$bgmessage" --inputbox "domain?" $defaultdomain
local domain="$dialogresult"
# username
graph "$bgmessage" --inputbox "username?"
local username="$dialogresult"
# architecture
graph "$bgmessage" --menu "architecture?" "amd64 64bit_kernel i386 32bit_kernel"
local arch="$dialogresult"
# memory
graph "$bgmessage" --menu "memory?" "256 MB 512 MB 1024 MB 2048 MB 4096 MB 8192 MB"
local mem="$dialogresult"
# rootsize
graph "$bgmessage" --menu "rootsize?" "4 GB 8 GB 16 GB 32 GB 64 GB 128 GB"
local rootsize="$dialogresult"
# swapsize
graph "$bgmessage" --menu "swapsize?" "512 MB 1024 MB 2048 MB 4096 MB 8192 MB"
local swapsize="$dialogresult"
# ubuntu release
graph "$bgmessage" --menu "ubuntu release?" "lucid 10.04_long_term hardy 8.04_long_term maverick 10.10"
local release="$dialogresult"
# network configuration
graph "$bgmessage" --inputbox "ip address?"
local ip="$dialogresult"
graph "$bgmessage" --inputbox "netmask?"
local netmask="$dialogresult"
graph "$bgmessage" --inputbox "gateway?"
local gateway="$dialogresult"
graph "$bgmessage" --inputbox "dns server(s)?"
local dns="$dialogresult"
# mirrors
local mirrorlist="$defaultmirror default_mirror http://at.archive.ubuntu.com/ubuntu official_austria_mirror http://ftp.halifax.rwth-aachen.de/ubuntu uni_aachen"
graph "$bgmessage" --menu "mirror?" "$mirrorlist"
local mirror="$dialogresult"
# cpus
graph "$bgmessage" --menu "cpus?" "1 singlecore 2 dualcore 4 quadcore 8 insane"
local cpus="$dialogresult"
# local network bridges
local bridgelist=$(ifconfig | grep HWaddr | awk '{print $1}' | grep br)
local localbridges=""
for var in $bridgelist; do
local localbridges="$localbridges $var local_network_bridge"
done
graph "$bgmessage" --menu "network?" "$localbridges"
local bridge="$dialogresult"
# timezone
#local timezonelist="Europe/Vienna GMT+1"
#graph "$bgmessage" --menu "timezone?" "$timezonelist"
#local timezone="$dialogresult"
local timezone="Europe/Vienna"
# additional software
for var in $recpackages; do
local packagegraph="$packagegraph $var recommended on"
done
for var in $optpackages; do
local packagegraph="$packagegraph $var optional off"
done
graph "$bgmessage" --checklist "additional software?" "$packagegraph"
local packagelist="${dialogresult//\"/ }"
for var in $packagelist; do
local addpkg="$addpkg --addpkg $var"
done
# select firstboot script
#graph "$bgmessage" --fselect ~/
graph "$bgmessage" --fselect $repopath/firstboot.sh
local firstboot="$dialogresult"
#calculate rootsize
local rootsize=$((rootsize*1024))
#gen password
local password=$(pwgen -snc 10 1)
local text=$(echo "hostname: $hostname
domain: $domain
user: $username
cpus: $cpus
memory: $mem
ip: $ip
release: $release
architecture: $arch
rootsize: $rootsize
swapsize: $swapsize
network: $bridge
mirror: $mirror
firstboot: $firstboot
continue?
(CTRL+C will kill the creation process)
")
graph "$bgmessage" --yesno "$text"
local proceed=$?
done
clear
log debug "mkjeos - creation of $hostname started. this can take a while, so please be patient."
vmbuilder kvm ubuntu --verbose --mem="$mem" --cpus="$cpus" --rootsize="$rootsize" --swapsize="$swapsize" --domain="$domain" --user="$username" --pass="$password" --suite="$release" --flavour=virtual --mirror="$mirror" --security-mirror="$mirror" --timezone="$timezone" --arch="$arch" --hostname="$hostname" --libvirt="qemu:///system" --bridge="$bridge" --ip="$ip" --mask="$netmask" --gw="$gateway" --dns="$dns" $addpkg --firstboot=$firstboot --destdir="$imagepath/tmpvmbuilder" &> /tmp/builderlog
if [ $? = "0" ]; then
log info "mkjeos - $hostname successfully created"
# removing temporary builderlog
rm /tmp/builderlog
# moving imagefile, redefining xml (changing image path)
mv $imagepath/tmpvmbuilder/tmp* $imagepath/$hostname"_"system.qcow2
rm -r $imagepath/tmpvmbuilder
local image=$(getimgpath $hostname)
getxmlpath $hostname
sed -i 's/'${image//\//\\\/}'/'${imagepath//\//\\\/}'\/'$hostname'_system.qcow2/' $xmlpath
virsh define $xmlpath
# run env fix
fix
# start the machine?
graph "$bgmessage" --yesno "everything is done, do you want to start $hostname now?"
local startvm=$?
if [ $startvm = 0 ]; then
virsh start $hostname
fi
# log
log info "mkjeos - hostname=$hostname.$domain, user=$username, password=$password release=$release, arch=$arch, size=$rootsize, swap=$swapsize, network=$bridge, ip=$ip, mirror=$mirror"
# machine details output
clear
echo
echo "machine details"
echo
echo "hostname=$hostname.$domain"
echo "user=$username"
echo "password=$password"
echo "release=$release"
echo "arch=$arch"
echo "size=$rootsize"
echo "swap=$swapsize"
echo "network=$bridge"
echo "ip=$ip"
echo "mirror=$mirror"
echo
else
log error "mkjeos - there was an error creating virtual machine $hostname"
exit 1
fi
}
# end of functions

122
kvm-tools/kvm-tools.sh Executable file
View File

@ -0,0 +1,122 @@
#!/bin/bash
#########################################
## ##
## kvm-tools ##
## ##
#########################################
# **** configuration section ****
# do not touch as long as you are not me
version="0.2_beta1"
author="david@socialnerds.org"
giturl="git://git.aec.at/kvm-tools.git"
functionfile="kvm-tools.func"
configfile="/etc/kvm-tools.conf"
logwhat="kvm-tools"
# **** bash trap initialisation ****
trap bashtrap INT
# **** read config file ****
if [ -r $configfile ]; then
source $configfile
else
echo "ERROR: configuration file not found."
exit 1
fi
# **** read function definitions ****
if [ -r $repopath/$functionfile ]; then
source $repopath/$functionfile
else
echo "ERROR: functionfile not found."
exit 1
fi
# **** load bashlib ****
if [ -d $bashlibpath ]; then
source $bashlibpath/main
source $bashlibpath/update
source $bashlibpath/logengine
log debug "preflight - bashlib loaded"
else
echo "ERROR: bashlib not found"
exit 1
fi
# **** option handler ****
while getopts "h,c:,e:,i,a:,b:,u,v,f" OPTION; do
case $OPTION in
h)
usage
log debug "option handler - usage message printed"
exit 0
;;
c)
log debug "option handler - server deployment process for $OPTARG started"
mkjeos "$OPTARG"
errorcode=$?
log debug "option handler - server deployment for $OPTARG finished"
exit $errorcode
;;
e)
edit "$OPTARG"
errorcode=$?
exit $errorcode
;;
i)
newids
exit $?
;;
a)
addimage "$OPTARG"
exit $?
;;
b)
log info "option handler - starting backup process"
backup "$OPTARG"
errorcode=$?
if [ $errorcode = "0" ]; then
log info "option handler - backup process successfully finished"
else
log error "option handler - an error occured during backup process"
fi
exit $errorcode
;;
u)
update
exit $?
;;
v)
version
exit $?
;;
f)
fix
exit $?
;;
?)
usage
exit 1
;;
esac
done
# **** print usage message if no option is given ****
if [ -z $1 ]; then
usage
exit 1
fi
# **** end of script ****
exit 0

9
lifesaver.pl Executable file
View File

@ -0,0 +1,9 @@
#!/usr/bin/perl
#source: http://www.etherealbits.com/2012/06/the-perl-script-that-may-save-your-life/
open(DEV, '/dev/sda1') or die "Can't open: $!\n";
while (read(DEV, $buf, 4096)) {
print tell(DEV), "\n", $buf, "\n"
if $buf =~ /stringtosearchfor/;
}

101
linz_ag.pl Executable file
View File

@ -0,0 +1,101 @@
#!/usr/bin/perl
use warnings;
use strict;
use Data::Dumper;
use LWP::Simple;
use XML::Simple;
use constant LINZ_AG_URL => "http://www.linzag.at/static/XML_DM_REQUEST";
sub get_trips {
my ( $name_dm, $no_of_trips ) = @_;
my ( $result, $result_trips, $requestID, $sessionID, $direction,
$max_length_dest, $max_length_countdown, $max_length_line );
$requestID = $sessionID = $max_length_dest = $max_length_countdown = $max_length_line = 0;
# cheat sheet:
# http://www.linzag.at/static/XML_DM_REQUEST?sessionID=0&locationServerActive=1&type_dm=any&name_dm=60502280
# http://www.linzag.at/static/XML_DM_REQUEST?sessionID=2880156875&requestID=1&dmLineSelectionAll=1
# open session and get ID
my $get_s_id_url = LINZ_AG_URL
. "?sessionID=${sessionID}"
. "&locationServerActive=1" # TODO: What does this do?
. "&type_dm=any"
. "&name_dm=${name_dm}"
. "&limit=${no_of_trips}";
my $xml = XMLin(get( $get_s_id_url ));
# retrieve XML for trips
$sessionID = $xml->{sessionID};
my $get_time_url = LINZ_AG_URL
. "?sessionID=${sessionID}"
. "&requestID=${requestID}"
. "&dmLineSelectionAll=1";
$xml = XMLin(get( $get_time_url ));
# map direction shortcode_letters to names (e.g $direction->{27}->{R} = "Linz Auwiesen" );
foreach my $line (@{$xml->{itdDepartureMonitorRequest}->{itdServingLines}->{itdServingLine}} ) {
$direction->{$line->{number}}->{$line->{motDivaParams}->{direction}} = $line->{direction};
}
# parse trips
foreach my $trip (@{$xml->{itdDepartureMonitorRequest}->{itdDepartureList}->{itdDeparture}}) {
my $line = $trip->{itdServingLine}->{symbol};
my $dest_code = $trip->{itdServingLine}->{motDivaParams}->{direction};
my $destination = $direction->{$line}->{$dest_code};
my $countdown = $trip->{countdown};
my $hour = $trip->{itdDateTime}->{itdTime}->{hour};
my $minute = $trip->{itdDateTime}->{itdTime}->{minute};
$max_length_dest = length($destination) if ( length($destination) > $max_length_dest);
$max_length_countdown = length($countdown) if ( length($countdown) > $max_length_countdown);
$max_length_line = length($line) if ( length($line) > $max_length_line);
push (@$result_trips, {
line => $line,
destination => $destination,
countdown => $trip->{countdown},
hour => $hour,
minute => $minute,
});
}
$result->{trips} = $result_trips;
$result->{max_length_dest} = $max_length_dest;
$result->{max_length_countdown} = $max_length_countdown;
$result->{max_length_line} = $max_length_line;
return $result;
}
sub print_trips {
# quick hack
my $t = shift;
my $ml_dest = $t->{max_length_dest};
my $ml_cd = $t->{max_length_countdown};
my $ml_ln = $t->{max_length_line};
$ml_ln = length("line") if ( length("line") > $ml_ln );
$ml_cd = length("countdown") if ( length("countdown") > $ml_cd );
$ml_dest = length("destination") if ( length("destination") > $ml_dest );
my $total_line_length = $ml_ln + $ml_cd + $ml_dest + 21;
print ( " ". "=" x $total_line_length . "\n" );
# line destination countdown time
printf(" | %-${ml_ln}s %-${ml_dest}s %-${ml_cd}s %s |\n", "line", "destination", "countdown", "time" );
print ( " ". "=" x $total_line_length . "\n" );
$ml_cd -= length("(min) ");
$ml_cd += length(" ");
for my $entry ( @{$t->{trips}} ) {
printf(" | %-${ml_ln}s | %-${ml_dest}s | %-${ml_cd}d(min) | %02d:%02d h |\n",
$entry->{'line'}, $entry->{'destination'},
$entry->{'countdown'},
$entry->{'hour'}, $entry->{'minute'});
}
print ( " ". "-" x $total_line_length . "\n" );
}
my $name_dm = 60502280;
my $no_of_trips = 10;
my $trips = get_trips($name_dm, $no_of_trips);
#print Dumper($trips);
print_trips($trips);

27
lomount.sh Executable file
View File

@ -0,0 +1,27 @@
#!/bin/sh
# Mount partitions within a disk image file
# Author: P@adraigBrady.com
# V1.0 29 Jun 2005 Initial release
# V1.1 01 Dec 2005 Handle bootable (DOS) parititons
if [ "$#" -ne "3" ]; then
echo "Usage: `basename $0` <image_filename> <partition # (1,2,...)> <mount point>" >&2
exit 1
fi
if ! fdisk -v > /dev/null 2>&1; then
echo "Can't find the fdisk util. Are you root?" >&2
exit 1
fi
FILE=$1
PART=$2
DEST=$3
UNITS=$(fdisk -lu $FILE 2>/dev/null | grep "$FILE$PART " |
tr -d '*' | awk '{print $2}')
OFFSET=`expr 512 '*' $UNITS`
mount -o loop,offset=$OFFSET $FILE $DEST

125
mc.sh Executable file
View File

@ -0,0 +1,125 @@
#!/bin/bash
# ******** minecraft control script ********
# ******** using systemd + screen ********
# **** configuration ****
user=minecraft
path=/opt/$user
bold="\033[1m"
normal="\033[0m"
red="\033[31m"
green="\033[32m"
yellow="\033[33m"
# **** start of script ****
state()
{
if [ -r "$path/$2/minecraft_server.jar" ]; then
systemctl status $1@$2 > /dev/null
if [ $? -eq 0 ]; then
return 0
else
return 1
fi
else
return 2
fi
}
usage()
{
echo -e "usage: mc option <server>\n\n ${bold}Servers:${normal}"
servers=$(ls -l $path | grep '^d' | awk '{print $9}')
for server in $servers; do
state $user $server
if [ $? -eq 0 ]; then
echo -e " [${green}${normal}] $server"
else
echo -e " [${red}${normal}] $server"
fi
done
echo -e "\n ${bold}Options:${normal}
help Print usage message
status Print server(s)
start <server> Start server instance
stop <server> Stop server instance
console <server> Connect to server console\n"
}
case "$1" in
h|help|-h|--help|status|a|-a|--status|l|ls|list|-l|--list)
usage
;;
s|start|-s|--start)
if [ $2 ]; then
state $user $2
value=$?
if [ $value -eq 0 ]; then
echo -e "\n [${yellow}${normal}] Server already up.($2)\n"
elif [ $value -eq 1 ]; then
echo -e "\n [${green}${normal}] Starting server.($2)\n"
sudo systemctl restart $user@$2
else
echo -e "\n [${red}${normal}] Server does not exist.($2)\n"
exit 1
fi
else
echo -e "\n [${red}${normal}] No server given.\n"
exit 1
fi
;;
t|stop|-t|--stop)
if [ $2 ]; then
state $user $2
value=$?
if [ $value -eq 0 ]; then
echo -e "\n [${yellow}${normal}] Stopping server. Sending 10 second notice.($2)"
sudo systemctl stop $user@$2
echo -e " [${green}${normal}] Stopped server.($2)\n"
elif [ $value -eq 1 ]; then
echo -e "\n [${yellow}${normal}] Server already down.($2)\n"
else
echo -e "\n [${red}${normal}] Server does not exist.($2)\n"
exit 1
fi
else
echo -e "\n [${red}${normal}] No server given.\n"
exit 1
fi
;;
c|console|-c|--console)
if [ $2 ]; then
state $user $2
value=$?
if [ $value -eq 0 ]; then
echo -e "\n [${yellow}${normal}] Connecting to server console on $user@$2."
echo -e " [${yellow}${normal}] Exit console with: ${bold}Strg-a d${normal}\n"; sleep 5
sudo -u $user /usr/bin/screen -R mc-$2
elif [ $value -eq 1 ]; then
echo -e "\n [${red}${normal}] Server not up.($2)\n"
exit 1
else
echo -e "\n [${red}${normal}] Server does not exist.($2)\n"
exit 1
fi
else
echo -e "\n [${red}${normal}] No server given.\n"
exit 1
fi
exit 0
;;
*)
usage
exit 1
;;
esac
exit 0
# **** end of script ****

156
mediacontrol.sh Normal file
View File

@ -0,0 +1,156 @@
#!/bin/bash
#################################
# ##
# mediacenter control script ##
# ##
#################################
# **** config section ****
author="david@socialnerds.org"
version="0.1_alpha"
hwaddr="00:10:c6:cd:00:d4" #mc mac address
ipaddr="10.1.1.7" #mc ip address/hostname
wolserv="10.1.1.4" #remote wakeonlan host (connects via ssh)
remoteuser="media" #mc user
mediapath="/home/media/Videos" #remote basepath for mediafiles
# check for dependencies
#apt-get install wakeonlan dialog
# **** bashtrap ****
# bash trap function is executed when CTRL-C is pressed
bashtrap()
{
log 3 "bashtrap - triggered"
clear
echo "CTRL+C detected.. exiting!"
exit 1
}
navigation()
{
dialog --backtitle "Media Center Control" --title "Navigation" --no-cancel --menu "" 13 55 7 start "start mediacenter" stop "shutdown mediacenter" vnc "open vnc session" play "play mediafile" kill "kill mediaplaybak" volume "control volume" quit "leave media control" 2> /tmp/dialog
navresult=$(cat /tmp/dialog)
rm /tmp/dialog
if [ $navresult = start ]; then
startmc
elif [ $navresult = stop ]; then
stopmc
elif [ $navresult = vnc ]; then
vncconnect
elif [ $navresult = play ]; then
playmedia
elif [ $navresult = kill ]; then
killmedia
elif [ $navresult = volume ]; then
volumecontrol
elif [ $navresult = quit ]; then
exit 0
fi
}
isitup()
{
# is mediacenter up?
clear
echo "checking if mediacenter is up..."
ping -w 1 $ipaddr &> /dev/null
local pingresult=$?
return $pingresult
}
startmc()
{
# check if mediacenter is up
isitup
if [ $? = 0 ]; then
dialog --backtitle "Media Center Control" --title "Info" --msgbox "\n\n mediacenter@$ipaddr is already up and running" 9 55
else
ssh $wolserv wakeonlan $hwaddr &> /dev/null
dialog --backtitle "Media Center Control" --title "Info" --msgbox "\n\n magic package sent to mediacenter@$ipaddr" 9 55
fi
}
stopmc()
{
# is mediacenter up?
isitup
if [ $? = 0 ]; then
ssh $remoteuser@$ipaddr "sudo shutdown -h now"
dialog --backtitle "Media Center Control" --title "Info" --msgbox "\n\n mediacenter@$ipaddr will be shutdown" 9 55
else
dialog --backtitle "Media Center Control" --title "Info" --msgbox "\n\n mediacenter@$ipaddr unreachable" 9 55
fi
exit 0
}
vncconnect()
{
# check if mediacenter is up
isitup
if [ $? = 0 ]; then
vncviewer $ipaddr &> /dev/null &
else
dialog --backtitle "Media Center Control" --title "Info" --msgbox "\n\n mediacenter@$ipaddr unreachable" 9 55
fi
}
playmedia()
{
file="/home/media/Videos/series/the_big_bang_theory/season_4/BBTIV.14.avi"
# check if mediacenter is up
isitup
if [ $? = 0 ]; then
# selecting file
ssh -t $remoteuser@$ipaddr "dialog --fselect $mediapath 7 70 2> /tmp/dialog"
local file=$(ssh $remoteuser@$ipaddr "cat /tmp/dialog && rm /tmp/dialog")
ssh $remoteuser@$ipaddr "export DISPLAY=:0.0 && vlc --no-video-title-show -f $file &> /dev/null" &
else
dialog --backtitle "Media Center Control" --title "Info" --msgbox "\n\n mediacenter@$ipaddr unreachable" 9 55
fi
}
killmedia()
{
# check if mediacenter is up
isitup
if [ $? = 0 ]; then
ssh $remoteuser@$ipaddr "killall vlc && killall rhythmbox"
else
dialog --backtitle "Media Center Control" --title "Info" --msgbox "\n\n mediacenter@$ipaddr unreachable" 9 55
fi
}
# **** volume control ****
volumecontrol()
{
# check if mediacenter is up
isitup
if [ $? = 0 ]; then
# open up remote alsamixer
ssh -t $remoteuser@$ipaddr alsamixer
else
dialog --backtitle "Media Center Control" --title "Info" --msgbox "\n\n mediacenter@$ipaddr unreachable" 9 55
fi
}
# ****** start of actual script ******
# **** bash trap initialisation ****
trap bashtrap INT
# **** run navigation ****
# endless loop
while [ 1 ]; do
navigation
done
exit 0
# end of script

12
mem.sh Normal file
View File

@ -0,0 +1,12 @@
#!/bin/bash
# used mem
umem=$(free -m | grep buffers/cache | awk '{print $3}')
tmem=$(free -m | grep Mem: | awk '{print $2}')
percent=$((100*$(free -m | grep buffers/cache | awk '{print $3}')/$(free -m | grep Mem: | awk '{print $2}')))
echo "Used memory: $percent% ($umem"MB"/$tmem"MB")"

View File

@ -0,0 +1,13 @@
#!/bin/bash
curl --silent http://torrent.ubuntu.com/simple/precise/server/ | grep beta2 >> /dev/null
if [ $? -eq 1 ]; then
#send mail
/home/david/SparkleShare/docs/scripts/telnet_mail.sh "Ubuntu 12.04 Precise Pangolin LTS is out."
else
echo "still beta2 online"
fi
exit 0

View File

@ -0,0 +1,15 @@
# **** list of uuids to monitor ****
#put this file in /etc/mbots and rename it to
#"diskmon.lst" or use a custom file as first
#option.
#ex.
#76c2a7e3-8765-4bb2-9093-ce495edb3833 90 98
#or
#UUID="76c2a7e3-8765-4bb2-9093-ce495edb3833" 90 98
#or
#/dev/sdb1 90 95
#<disk> <threshold1> <threshold2>

121
monitoring/diskmon.sh Normal file
View File

@ -0,0 +1,121 @@
#!/bin/bash
#\
# \_ _ _ _ _ _ _ _ _ _ _ _ _
# #\
# # \
# disk usage monitoring # \
# script # /
# # /
# _ _ _ _ _ _ _ _ _ _ _ _ _#/
# /
#/
# **** config section ****
#do not touch as long as you're not me
author="david@socialnerds.org"
version="0.1"
giturl="git://git.aec.at/mbots.git"
configfile="/etc/mbots/mbots.conf"
log2stdout="1"
logwhat="mbots_diskmon"
file="/etc/mbots/diskmon.lst"
# **** preflight ****
#read configfile
if [ -r $configfile ]; then
source $configfile
else
echo "ERROR: configfile not found. terminating."
exit 1
fi
#load bashlib
if [ -d $bashlibpath ]; then
source $bashlibpath/main
source $bashlibpath/logengine
log debug "preflight - logengine loaded"
else
echo "ERROR: bashlib not found. terminating."
exit 1
fi
#check environment
log info "**** starting disk monitoring bot ****"
#first option triggers custom list
if [ -z $1 ]; then
log debug "preflight - no custom list given. using $file[default]"
else
file=$1
log debug "preflight - list option given. using $file"
fi
# read file
linecount="1"
while read line; do
#find first letter to determine if line is empty or a comment
fletter=${line:0:1}
#check for first letter
if [ -z $fletter ]; then
#skip line it's empty
log debug "skipping line $linecount in $file: it's empty"
elif [ $fletter = "#" ]; then
#skip line it's a comment
log debug "skipping line $linecount in $file: it's a comment"
else
#read line
log debug "reading line $linecount in $file"
#getting values
disk=$(echo $line | awk '{print $1}')
th1=$(echo $line | awk '{print $2}')
#if threshold2 not given set th2 eq th1
th2=$(echo $line | awk '{print $3}')
if [ -z $th2 ]; then
th2=$th1
fi
devstring=$(blkid | grep $disk | awk '{print $1}')
uuidstring=$(blkid | grep $disk | awk '{print $2}')
devname=$(echo ${devstring::$((${#devstring}-1))})
uuid=$(echo ${uuidstring:6:$((${#uuidstring}-7))})
#getting diskusage
diskusage=$(df -hP --sync | grep $devname | awk '{print $5}')
diskusage=$(echo ${diskusage::$((${#diskusage}-1))})
if [ $diskusage -gt $th2 ]; then
#error, reached threshold2
log error "$devname uses $diskusage% of disk space (warn: $th1%, err: $th2%)"
elif [ $diskusage -gt $th1 ]; then
#warning, reached threshold1
log warning "$devname uses $diskusage% of disk space (warn: $th1%, err: $th2%)"
else
#info, everything ok
log info "$devname is at $diskusage% (warn: $th1%, err: $th2%)"
fi
fi
#linecount +1
let linecount++
#source file to read (diskmon.lst)
done < $file
#battlestar galactica fun section :-)
log debug "adama: what do you hear starbuck?"
log debug "kara: nothin' but the rain sir!"
log info "**** disk monitoring bot finished ****"
# **** end of script ****

14
monitoring/free.sh Normal file
View File

@ -0,0 +1,14 @@
#!/bin/bash
freememory=$(free -m | grep "cache:" | awk '{print $4}')
threshold="300"
if [ $freememory -gt $threshold ]; then
echo "There is $freememory MB availible. Threshold not reached."
else
echo "There is less than $threshold MB of memory availible."
/home/david/mail.sh "There is less than $threshold MB of memory availible!! You should probably do something about that pretty soon brother!!"
fi
exit 0

22
monitoring/get_uptime.sh Normal file
View File

@ -0,0 +1,22 @@
#!/bin/bash
# get uptimes of linux machines
array="localhost
blade9.aec.at
blade10.aec.at
blade11.aec.at
blade12.aec.at
blade13.aec.at
blade15.aec.at
nymeria.aec.at
walter.aec.at
search.aec.at
webarchive.aec.at
prix.aec.at
git.aec.at"
for machine in $array; do
echo "$machine: $(ssh -q $machine uptime)"
done

113
monitoring/heartbeat.sh Normal file
View File

@ -0,0 +1,113 @@
#!/bin/bash
#
# heartbeat survaillance
# script
#
# **** config section ****
author="david@socialnerds.org"
version="0.1"
sourcefile="/etc/hosts"
excludes="127.0.0.1 127.0.1.1 ::1 fe00::0 ff00::0 ff02::1 ff02::2 ff02::3"
options="-n -c 5 -i 0.2 -W 1"
maxloss="20%"
log2stdout="1"
logwhat="mbots_heartbeat"
configfile="/etc/mbots/mbots.conf"
giturl="git://git.aec.at/mbots.git"
# **** preflight ****
#read configfile
if [ -r $configfile ]; then
source $configfile
else
echo "ERROR: configfile not found. terminating."
exit 1
fi
#load bashlib
if [ -d $bashlibpath ]; then
source $bashlibpath/main
source $bashlibpath/logengine
log debug "preflight - logengine loaded"
else
echo "ERROR: bashlib not found. terminating."
exit 1
fi
# **** function definition ****
check()
{
local ip=$1
echo $ip | grep ":" &> /dev/null
local isv4=$?
if [ $isv4 = "1" ]; then
# run ipv4 ping
local value=$(ping $options $ip | grep -o -e "[0-9]*%")
elif [ $isv4 = "0" ]; then
# run ipv6 ping
local value=$(ping6 $options $ip | grep -o -e "[0-9]*%")
fi
if [ ${value:0:$((${#value}-1))} -gt ${maxloss:0:$((${#maxloss}-1))} ]; then
log error "not able to reach $(echo $line | awk '{print $2}') at $ip"
fi
}
# **** start of script ****
# set linecount to 1
linecount="1"
# read line by line of $sourcefile
while read line; do
#get first letter of line
fletter=${line:0:1}
if [ -z $fletter ]; then
#skip line, it's empty
:
elif [ $fletter = "#" ]; then
#skip line, it's a comment
:
else
#exclusion of $excludes
excluded="0"
for var in $excludes; do
#check if ip is excluded
if [ $(echo $line | awk '{print $1}') = $var ]; then
excluded="1"
break
fi
done
#run check function for ip if not excluded
if [ $excluded = "1" ]; then
continue
else
#run actual ping
check "$(echo $line | awk '{print $1}')"
fi
fi
#count lines
let linecount++
done < $sourcefile
exit 0
# **** end of script ****

View File

@ -0,0 +1,15 @@
# central mbots configuration file
#this file must be in /etc/mbots
#bashlib location
bashlibpath="/opt/bashlib"
#logging
loglevel="4"
log2file="0"
logfile=/var/log/mbots.log
log2syslog="1"

45
monitoring/system.sh Normal file
View File

@ -0,0 +1,45 @@
#!/bin/sh
# file: system.sh
# version: 0.1
# author: david@socialnerds.org
#
# description: this script checks for local system health and
# fires if values exeed a certain threshold
#
# changelog: [11/22/2020] - file created
# **** configuration ****
CHECKS="load memory disk_usage"
# **** functions ****
load() {
local THRESHOLD=$1
}
memory() {
pass
}
disk_usage() {
pass
}
# **** loop through checks
for CHECK in $CHECKS; do
pass
done
# ping on success
# ping ../fail on failure
# provide payload (log output/error message)
exit 0

11
on_time.sh Executable file
View File

@ -0,0 +1,11 @@
#!/bin/bash
#count minutes since start
minutes=0
while true; do
sleep 60
minutes=$(($minutes+1))
echo $minutes
done

12
ping.conf.sample Normal file
View File

@ -0,0 +1,12 @@
# a whitespace seperated list of ip addresses or fqdnames
dest="192.168.1.13 somemachine.example.com"
# jabber configuration
user="jid"
server="jabber-server"
#port="" ## if you want to use a special port (default: 5222)
pass="jabber-password"
res="pingbot"
watchdogs="someuser@jabber.example.com anotheruser@example.com" ## whitespace seperated list of JIDs

98
ping.sh Normal file
View File

@ -0,0 +1,98 @@
#!/bin/bash
## ## ## ## ## ## ## ## ##
## ##
## jabber ping bot ##
## ##
## v0.1 ##
## ##
## author: david@socialnerds.org ##
## ##
## ## ## ## ## ## ## ## ##
## timestamp for logfile
timestamp=$(date '+%d %B %Y %H:%M')
echo "info: starting jabber ping bot $timestamp"
## check if sendxmpp is installed
if [ $(aptitude search sendxmpp | awk '{print $1}') = "i" ]; then
echo "info: sendxmpp found"
else
if [ $(whoami) = "root" ]; then
apt-get install sendxmpp
else
echo "error: permission denied"
echo "info: install sendxmpp or run this scrip as superuser"
exit 1
fi
fi
## set and load configfile
if [ -z $1 ]; then
configfile="/etc/mobots/ping.conf"
if [ -f $configfile ]; then
source $configfile
else
echo "error: no config file $configfile"
exit 1
fi
else
configfile=$1
if [ -f $configfile ]; then
source $configfile
else
echo "error: no config file $configfile"
exit 1
fi
fi
## check sendxmpp config
if [ -f ~/.sendxmpprc ]; then
echo "info: jabber config found in ~/.sendxmpprc"
else
if [ -z $port ]; then
port="5222"
else
echo "info: using port $port"
fi
echo "$user@$server:$port $pass" > ~/.sendxmpprc
chmod 600 ~/.sendxmpprc
echo "info: created sendxmpp config in ~/.sendxmpprc"
fi
## run the actual ping
set -- $dest
for var in "$@"
do
#result=$(ping -c 05 $var | grep transmitted | awk '{print $4}')
ping -c 03 $var >/dev/null 2>&1
errorcode=$?
if [ $errorcode = "0" ]; then
echo "info: $var is responding"
else
if [ $errorcode = "1" ]; then
echo "alert: $var is not responding"
## sending jabber message
echo "alert: $var is not responding
ping errorcode: $errorcode" | sendxmpp -r $res $watchdogs
else
if [ $errorcode = "2" ]; then
echo "alert: $var cannot be resolved"
## sending jabber message
echo "alert: $var cannot be resolved
ping errorcode: $errorcode" | sendxmpp -r $res $watchdogs
fi
fi
fi
done
## the end
exit 0

139
power_control.sh Executable file
View File

@ -0,0 +1,139 @@
#!/bin/bash
#
# control my hs100 power switches
#
VERSION="0.1"
AUTHOR="david@socialnerds.org"
DEVICES="media ghost"
is_status_on() {
if [ "$1" ] && [ $(./hs100/hs100.sh -i power-$1.socialner.ds check | awk '{print $2}') == "ON" ]; then
return 0
else
return 1
fi
}
is_status_off() {
if [ "$1" ] && [ $(./hs100/hs100.sh -i power-$1.socialner.ds check | awk '{print $2}') == "OFF" ]; then
return 0
else
return 1
fi
}
does_device_exist() {
if [ "$1" ]; then
for DEVICE in $DEVICES; do
if [ "$1" == $DEVICE ]; then
return 0
fi
done
return 1
else
return 1
fi
}
switch_device_on() {
if [ "$1" ]; then
./hs100/hs100.sh -i power-$1.socialner.ds on
if [ $? -ne 0 ]; then
return 1
fi
return 0
else
return 1
fi
}
switch_device_off() {
if [ "$1" ]; then
./hs100/hs100.sh -i power-$1.socialner.ds off
if [ $? -ne 0 ]; then
return 1
fi
return 0
else
return 1
fi
}
print_usage() {
echo "usage: ./power_control <on|off|status> <device>"
}
# **** start of script ****
if [ "$1" ] && [[ "$1" == @("on"|"off"|"status") ]] && [ "$2" ]; then
if does_device_exist $2; then
case $1 in
"on")
if is_status_off $2; then
echo "switching on $2"
if ! switch_device_on $2; then
echo "error: something went wrong while switching on device"
exit 1
fi
sleep 2
if is_status_on $2; then
echo "$2 switched on successfully"
else
echo "warning: device still appears off"
fi
else
if is_status_on $2; then
echo "warning: device is already switched on"
else
echo "error: something went wrong while checking device status"
exit 1
fi
fi
;;
"off")
if is_status_on $2; then
echo "switching off $2"
if ! switch_device_off $2; then
echo "error: something went wrong while switching off device"
exit 1
fi
sleep 2
if is_status_off $2; then
echo "$2 switched off successfully"
else
echo "warning: device still appears on"
fi
else
if is_status_off $2; then
echo "warning: device is already switched off"
else
echo "error: something went wrong while checking device status"
exit 1
fi
fi
;;
"status")
if is_status_on $2; then
echo "$2 is on"
elif is_status_off $2; then
echo "$2 is off"
else
echo "error: something went wrong while getting device status"
exit 1
fi
;;
esac
else
echo "error: device unknown"
print_usage
exit 1
fi
else
echo "error: command unknown"
print_usage
exit 1
fi
# **** end of script ***

83
prep_ubuntu_server.sh Executable file
View File

@ -0,0 +1,83 @@
#!/bin/bash
# preperation script for my ubuntu servers
# **** configuration section ****
sshgroup="sshusers"
#user=$(cat /etc/passwd | grep 1000)
#user=${user:0:$(($(echo `expr index "$user" :`)-1))}
user="david"
# **** install various tools/packages ****
pkginstall()
{
apt-get update
apt-get dist-upgrade -y
apt-get install -y htop nload nmap tshark git-core \
curl wget dnsutils \
vim zsh ncdu
}
# **** configure motd ****
motdconfig()
{
rm /etc/update-motd.d/00*
rm /etc/update-motd.d/10*
rm /etc/update-motd.d/50*
echo ""
read -p "now its time to create/customize your /etc/motd.tail
(go to http://www.network-science.de/ascii/)"
vim /etc/motd.tail
}
# **** ssh server config ****
sshdconfig()
{
echo "
__.-._
'-._'7'
/'.-c
| /T
_)_/LI
this machine is
protected by a
master of the force!
" > /etc/issue.net
sed -i 's/#Banner/Banner/' /etc/ssh/sshd_config
echo "" >> /etc/ssh/sshd_config
echo "# Restrictions added by ubuntu server prep script" >> /etc/ssh/sshd_config
echo "AllowGroups $sshgroup" >> /etc/ssh/sshd_config
echo "" >> /etc/ssh/sshd_config
addgroup $sshgroup
adduser $user $sshgroup
read -p "add needed users to sshgroup $sshgroup in /etc/group"
vim /etc/group
}
# **** start of script ****
pkginstall
motdconfig
sshdconfig
exit 0
# **** end of file ****

40
prime.pl Executable file
View File

@ -0,0 +1,40 @@
#!/usr/bin/env perl
# prime number calculation
# author: david@socialnerds.org
my $num = 3;
print "highest prime number: ";
chomp(my $maxnum = <STDIN>);
my $count = 2;
print "2\n3\n";
while ( $num <= $maxnum )
{
$i=3;
while ( $i <= int($num**(1/2)+1) )
{
if ( $i != 1 && $i < $num && $i%2 != 0 )
{
if ( $num % $i != 0 ) {
$probably = "true"
} else {
$probably = "false";
last;
}
}
$i += 2;
}
if ( $probably eq "true" )
{
print "$num\n";
$count++;
}
$num += 2;
}
print "prime number count: $count\n";

47
recreate_ssh_host_keys.sh Executable file
View File

@ -0,0 +1,47 @@
#!/bin/bash
#
# recreate ssh host keys
#
sshdconfig="/etc/ssh/sshd_config"
if [ $(whoami) != "root" ]; then
echo "you need to be root"
exit 1
fi
if [ -r $sshdconfig ]; then
while read line; do
fletter=${line:0:1}
if [ -z $fletter ]; then
#empty line. skipping.
:
elif [ $fletter == "#" ]; then
#comment. skipping.
:
else
echo $line | grep "HostKey" >> /dev/null
if [ $? -eq 0 ]; then
file=$(echo $line | awk '{print $2}')
if [ $file != "${file/_dsa_/}" ]; then
mv $file $file.old
mv $file.pub $file.pub.old
ssh-keygen -t dsa -f $file
elif [ $file != "${file/_ecdsa_/}" ]; then
mv $file $file.old
mv $file.pub $file.pub.old
ssh-keygen -t ecdsa -f $file
elif [ $file != "${file/_rsa_/}" ]; then
mv $file $file.old
mv $file.pub $file.pub.old
ssh-keygen -t rsa -f $file
fi
fi
fi
done < $sshdconfig
exit 0
else
echo "$sshdconfig - file not found"
exit 1
fi

52
reference.pl Executable file
View File

@ -0,0 +1,52 @@
#!/usr/bin/env perl
use 5.010;
my $var = 5*5;
chomp(my $input = <STDIN>);
$var *= $input;
if ( $var == 100 )
{
say $var;
}
else
{
say "it is not 100";
}
$is_true = $var == 100;
if ( ! $is_true )
{
say "not true";
}
else
{
say "true";
}
my $zaehler=0;
while ($zaehler <= 5)
{
say "der zähler steht jetzt auf $zaehler";
$zaehler += 1;
}
chomp(my $input2 = <STDIN>);
if ( defined($input2) )
{
say "eingabe lautet: $input2";
}
else
{
say "keine eingabe verfügbar";
}
#umfang berechnung
print "bitte radius für umfangberechnung angeben: ";
chomp(my $radius = <STDIN>);
my $umfang = $radius *= 2*3.141592654;
say "umfang beträgt: $umfang";

View File

@ -0,0 +1,61 @@
#!/usr/bin/perl -w
#
# pfdel - deletes message containing specified address from
# Postfix queue. Matches either sender or recipient address.
#
# Usage: pfdel <email_address>
#
use strict;
# Change these paths if necessary.
my $LISTQ = "/usr/sbin/postqueue -p";
my $POSTSUPER = "/usr/sbin/postsuper";
my $email_addr = "";
my $qid = "";
my $euid = $>;
if ( @ARGV != 1 ) {
die "Usage: pfdel <email_address>\n";
} else {
$email_addr = $ARGV[0];
}
if ( $euid != 0 ) {
die "You must be root to delete queue files.\n";
}
open(QUEUE, "$LISTQ |") ||
die "Can't get pipe to $LISTQ: $!\n";
my $entry = <QUEUE>; # skip single header line
$/ = ""; # Rest of queue entries print on
# multiple lines.
while ( $entry = <QUEUE> ) {
if ( $entry =~ / $email_addr$/m ) {
($qid) = split(/\s+/, $entry, 2);
$qid =~ s/[\*\!]//;
next unless ($qid);
#
# Execute postsuper -d with the queue id.
# postsuper provides feedback when it deletes
# messages. Let its output go through.
#
if ( system($POSTSUPER, "-d", $qid) != 0 ) {
# If postsuper has a problem, bail.
die "Error executing $POSTSUPER: error " .
"code " . ($?/256) . "\n";
}
}
}
close(QUEUE);
if (! $qid ) {
die "No messages with the address <$email_addr> " .
"found in queue.\n";
}
exit 0;

68
rtspstream.pl Executable file
View File

@ -0,0 +1,68 @@
#!/usr/bin/perl
# Author: Dominik Danter
# Version: 0.01
# Purpose:
# Tiny VLC wrapper that streams the file provided as argument. This can be used
# as a Nautlius-Script. It just works on one file yet.
#
# Just a litte Script that by default opens two instances of vlc.
#
# The first one will stream the passed files with the real time streaming
# protocol (rtsp) at $rtsspport. If the device $dev (e.g. 'eth0')
# has got a valid IPv4 address you can control the sever at
# {address of device}:$httpport. Note: localhost:$httpport will NOT work.
#
# If you do not wish this behaviour assign a false value to $httpport
# (my $httpport = 0; for example).
#
# You can control access to this webserver in the .hosts file
# (on ubuntu one can find this file in /usr/share/vlc/http).
#
# At the moment just one server instance will work.
#
# The second instance will indefinitely repeatedly listen on
# localhost:$rtspport and serves as the client, for local playback.
# If you do not wish local playblack assign a false value to
# $localplayback (my $localplayback = 0; for example);
#
# Todo:
# Check requirements first and die if they are not met.
# Implement a more versatile way of passing options to vlc.
# Support IPv6 by altering the regex.
use strict;
use warnings;
use v5.12;
#settings
my $dev = 'eth0'; #Your favourite interface here, maybe 'eth0';
my $httpport = 8080; #unsetting this will disable the webserver
my $rtspport = 5544;
my $localplayback = 1; #set to 0 if you do not wish local playback
#end settings
#if no arguments ar passed die
@ARGV > 0 or die "you forgot to pass some filenames to $0";
my $http = "";
#get ip addr of $dev
$_ = `ip addr show $dev`;
my ($address) = /inet ((\d\d?\.){3}\d\d?)/;
if ($address && $httpport) {
$http = "--extraintf http --http-host $address:$httpport ";
}
#escape arguments (samplemovie.avi to "samplemovie.avi");
@ARGV = map{ $_ = '"'.$_.'"' } @ARGV;
#start server
system "vlc @ARGV $http:sout=#rtp{sdp=rtsp://:$rtspport/} :no-sout-rtp-sap :no-sout-standard-sap :ttl=1 :sout-keep &";
#pause
sleep(1);
#start client if applicable
system "vlc --repeat rtsp://localhost:$rtspport/" if $localplayback;
#ich mag Schokolade gern

146
setup_zsh.sh Executable file
View File

@ -0,0 +1,146 @@
#!/usr/bin/env bash
#
# download and setup zsh, oh-my-zsh and various zsh plugins
#
# author: david@socialnerds.org
# license: MIT
# git: https://socialg.it/david/scripts.git
# version 0.1
# **** vars ****
command="$0"
root="$HOME/.dotfiles"
plugins="$root/zsh"
timestamp=$(date +"%Y%m%d%H%M")
debug=1
remove=".dotfiles .dotfiles.old .myzsh .oh-my-zsh .zshrc .zshrc-pre-oh-my-zsh"
dependencies="awk tee ls git wget curl rm mv sleep date"
if [ $(uname) == "Darwin" ]; then
alias sed="gsed"
#TODO: check if gsed is there first
fi
# **** functions ****
message() {
if [ $1 == "e" ]; then
level="\033[31m✗\033[0m"
elif [ $1 == "i" ]; then
level="\033[32m✓\033[0m"
elif [ $1 == "w" ]; then
level="\033[33m!\033[0m"
elif [ $1 == "d" ]; then
if [ $debug -eq 1 ]; then
level="\033[2md\033[0m"
else
return 0
fi
else
message e "Unknown message level[$1]."
return 1
fi
echo -e [$level] ${@:2}
sleep 0.1
}
failsafe() {
if [ $1 -ne 0 ]; then
message e "Installer died horribly!"
if [ $2 ]; then
message d "Dumping last output to stdout."
echo ${@:2}
fi
exit 1
fi
}
cleanup() {
# Get rid of preexisting data at destination
destination=$1
if [ -a "$destination.old" ]; then
message e "A previous backup exists. Move elsewhere or delete first[$destination.old]."
exit 1
else
if [ -h $destination ]; then
link=$(ls -la $destination | awk '{print $9" "$10" "$11}')
# It should be safe to just remove symbolic links because no data is actually deleted.
message d "Symbolic link exists, attempting to remove it[$link]."
output=$(rm $destination 2>&1); failsafe $? $output
message i "Removed symbolic link[$link]."
elif [ -a $destination ]; then
# Rename data to $destination.old
message d "Data exists at install destination, attempting to create a backup[$destination.old]."
output="", output=$(mv $destination $destination.old 2>&1); failsafe $? $output
message i "Created a backup of a preexisting data[$destination.old]."
fi
fi
}
# **** start of script ****
message d "Warming up installer."
#message d "Initiating preflight checks."
# check dependencies
missing=""
for item in $dependencies; do
command -v $item > /dev/null
if [ $? -ne 0 ]; then
missing="$missing $item"
fi
done
if [ -n "$missing" ]; then
message e "dependencies missing: $missing"
exit 1
fi
message i "all dependencies found"
# remove everything in 5 seconds: ~/.dotfiles ~/.dotfiles.old ~/.myzsh ~/.oh-my-zsh ~/.zshrc
message w "your old configs will be deleted in 5 seconds [terminate deletion with Ctrl-C]"
sleep 5
for item in $remove; do
if [ -d $item ]; then
rm -rf $HOME/$item
message w "removed folder: ~/$item"
elif [ -h $item ]; then
rm $HOME/$item
message w "removed link: ~/$item"
elif [ -f $item ]; then
rm $HOME/$item
message w "removed file: ~/$item"
fi
done
# invoke oh-my-zh installer
if [ -w $HOME ]; then
curl -fsSL https://raw.github.com/robbyrussell/oh-my-zsh/master/tools/install.sh | bash
message i "oh-my-zsh installed"
else
message e "oh-my-zsh could not be installed. $HOME is not writeable"
exit 1
fi
# clone plugins
cd $HOME/.oh-my-zsh/custom/plugins/ > /dev/null
git clone https://github.com/sindresorhus/pure.git pure
git clone https://github.com/mafredri/zsh-async.git async
git clone https://socialg.it/david/zsh-david.git zsh-david
git clone https://github.com/zsh-users/zsh-syntax-highlighting.git zsh-syntax-highlighting
git clone https://github.com/skx/sysadmin-util.git sysadmin-util
git clone https://github.com/TamCore/autoupdate-oh-my-zsh-plugins.git autoupdate
git clone https://github.com/zsh-users/zsh-autosuggestions.git zsh-autosuggestions
cd - > /dev/null
message i "all plugins cloned"
# set $ZSH_THEME="" in .zshrc
sed -i "s/^ZSH_THEME=\"robbyrussell\"/ZSH_THEME=\"\"/g" $HOME/.zshrc
# set $plugins in .zshrc
plugins="git zsh-autosuggestions autoupdate sysadmin-util zsh-syntax-highlighting zsh-david async pure"
sed -i "/plugins=(/,/)/d; s/source \$ZSH\/oh-my-zsh.sh/plugins=($plugins);; source \$ZSH\/oh-my-zsh.sh/g" $HOME/.zshrc
sed -i $'s/;; /\\\n/g' $HOME/.zshrc
message i "tweaked ~/.zshrc"
message d "Installer finished."
# **** end of script ****

12
speedtest.sh Normal file
View File

@ -0,0 +1,12 @@
#!/bin/bash
# simple speedtest logger
# install https://github.com/taganaka/SpeedTest first
server="speedcheck.liwest.at:8080"
options="--output text --test-server $server"
timestamp=$(date +%Y/%m/%d_%H:%M)
cmd="/usr/local/bin/SpeedTest"
result=$($cmd $options | grep -v IP_LAT | grep -v IP_LON | grep -v PROVIDER | grep -v TEST_SERVER_HOST)
echo $timestamp - $result

10
start_vmware.sh Executable file
View File

@ -0,0 +1,10 @@
#!/bin/bash
# Start local VMWare services and set permissions to vmnet0
sudo /etc/init.d/vmware start
sudo chgrp sudo /dev/vmnet0
sudo chmod g+rw /dev/vmnet0
sudo chgrp sudo /dev/vmnet1
sudo chmod g+rw /dev/vmnet1

57
telnet_mail.sh Executable file
View File

@ -0,0 +1,57 @@
#!/bin/bash
###############################
# #
# mbots mail routine #
# #
###############################
# ***** config section *****
#don't touch as long as you're not me. feel me?
version=".1"
author="david@socialnerds.org"
smtpserver="smtp.aec.at"
recipients="person@domain.tld person2@domain.tld"
from="releasechecker@aec.at"
subject="ubuntu precise pangolin is out. download it. seed it."
line=$1
#if [ -f $line ]; then
# line=$(cat $line)
#fi
# ***** start of script *****
#telnet connection
{
sleep 1
echo "HELO $HOSTNAME"
sleep 1
echo "MAIL FROM: $from"
sleep 1
for address in $recipients; do
echo "RCPT TO: $address"
sleep 1
done
echo "DATA"
sleep 1
for address in $recipients; do
echo "To: $address"
done
echo "From: Release CheckeR <$from>"
echo "Subject: $subject"
sleep 1
echo "$line"
sleep 1
echo "."
sleep 1
echo "QUIT"
} | telnet $smtpserver 25
# ***** end of script *****
#live long and prosper
exit 0

View File

@ -0,0 +1,18 @@
#!/bin/bash
# brightness - on my thinkpad
max=$(cat /sys/class/backlight/intel_backlight/max_brightness)
echo "Max: $max"
min=0
echo "Min: $min"
value=250
echo "Value: $value"
actual=$(cat /sys/class/backlight/intel_backlight/actual_brightness)
echo "Actual: $actual"
future=$(($actual-$value))
if [ $future -lt 0 ]; then
future=0
fi
echo "Future: $future"
tee /sys/class/backlight/intel_backlight/brightness <<< $future

18
thinkpad_x131e/brightness_up.sh Executable file
View File

@ -0,0 +1,18 @@
#!/bin/bash
# brightness + on my thinkpad
max=$(cat /sys/class/backlight/intel_backlight/max_brightness)
echo "Max: $max"
min=0
echo "Min: $min"
value=250
echo "Value: $value"
actual=$(cat /sys/class/backlight/intel_backlight/actual_brightness)
echo "Actual: $actual"
future=$(($actual+$value))
if [ $future -gt $max ]; then
future=$max
fi
echo "Future: $future"
tee /sys/class/backlight/intel_backlight/brightness <<< $future

View File

@ -0,0 +1,9 @@
#!/bin/bash
#fix thinkpad trackpoint
sleep 5
xinput set-prop "TPPS/2 IBM TrackPoint" "Evdev Wheel Emulation" 1
xinput set-prop "TPPS/2 IBM TrackPoint" "Evdev Wheel Emulation Button" 2
xinput set-prop "TPPS/2 IBM TrackPoint" "Evdev Wheel Emulation Timeout" 200
xinput set-prop "TPPS/2 IBM TrackPoint" "Evdev Wheel Emulation Axes" 6 7 4 5
xinput set-prop "TPPS/2 IBM TrackPoint" "Device Accel Constant Deceleration" 0.75

100
vpnc_config.sh Normal file
View File

@ -0,0 +1,100 @@
#!/bin/bash
clear
echo "
########################################################
#### Installation and configuration of vpnc ####
#### ####
#### Cisco VPN Config Script ####
#### ####
#### Scriptauthor: David Starzengruber ####
########################################################
"
# scriptconfiguration (if you want to skip the config wizard)
connection_name="aec"
vpn_user="<user>"
vpn_password="<password>"
vpn_gate="<ip>"
vpn_group="<vpn-group>"
vpn_group_password="<group-secret>"
command=""
# sudo check
if [ $USER != "root" ]; then
echo "
Sorry $USER, you need to run this script as user root! (try: sudo ./vpnc.sh)
"
exit
fi
# configuration wizard
clear
echo "Cisco VPN config wizard"
echo "Enter a name for this connection:"
read connection_name
clear
echo "Cisco VPN config wizard"
echo "Enter $connection_name VPN Gateway:"
read vpn_gate
clear
echo "Cisco VPN config wizard"
echo "Enter $connection_name VPN Username:"
read vpn_user
clear
echo "Cisco VPN config wizard"
echo "Enter $connection_name VPN Password:"
read vpn_password
clear
echo "Cisco VPN config wizard"
echo "Enter $connection_name VPN Group:"
read vpn_group
clear
echo "Cisco VPN config wizard"
echo "Enter $connection_name VPN Group Password:"
read vpn_group_password
clear
echo "Cisco VPN config wizard"
echo "Enter any command which should be executed on connect:"
read command
clear
# installation via package-manager
echo Installing vpnc..
apt-get install -y vpnc | grep already
# adding connection script
echo "Creating connection script. (/usr/local/bin/connect-$connection_name)"
echo "echo Starting VPNC Deamon..
sudo vpnc-connect /etc/vpnc/$connection_name.cfg
$command
echo Custom command executed.
" > /usr/local/bin/connect-$connection_name
# adding configuration file
echo "Creating $connection_name configuration file..."
echo "IPSec gateway $vpn_gate
IPSec ID $vpn_group
IPSec secret $vpn_group_password
Xauth username $vpn_user
Xauth password $vpn_password" > /etc/vpnc/$connection_name.cfg
#setting executeperms
chmod 775 /usr/local/bin/connect-$connection_name
#finish
echo "
########################################################
#### Installation and configuration of vpnc ####
#### ####
#### Cisco VPN Config Script ####
#### ####
#### Scriptauthor: David Starzengruber ####
########################################################
"
echo "Everythings done!
Configfilepath: /etc/vpnc/$connection_name.cfg
Startscriptpath: /usr/local/bin/connect-$connection_name
VPN connect command: connect-$connection_name
"

140
youtube_converter.sh Normal file
View File

@ -0,0 +1,140 @@
#!/bin/bash
# # # # # # # # # # # # # # # # # # # # #
# #
# YouTube Contvertion Tool #
# #
# Author: david@socialnerds.org #
# Version: v0.3 #
# #
# #
# # # # # # # # # # # # # # # # # # # # #
# help text
if [[ $1 == "-h" || $1 == "--help" ]]; then
echo "
# # # # # # # # # # # # # # # # # # # # #
# #
# YouTube Contvertion Tool #
# #
# Author: david@socialnerds.org #
# Version: v0.3 #
# #
# #
# # # # # # # # # # # # # # # # # # # # #"
echo
echo "usage: youtube_converter <mp3/mpeg> <youtube-link> <destination path>"
echo "hint: all options are optional"
echo
exit 0
fi
# checking dependencies (except browser, i use chromium here)
if [[ $(aptitude search ffmpeg | grep multimedia | awk '{print $1}') = "i" && $(aptitude search lame | grep frontend | awk '{print $1}') = "i" && $(aptitude search curl | grep "Get a file" | awk '{print $1}') = "i" ]]; then
#echo "info: all dependencies found"
:
else
if [ $(whoami) = "root" ]; then
echo "info: trying to insall missing dependencies"
apt-get install -y ffmpeg curl lame
echo "info: all dependencies installed. rerun script."
exit 0
else
echo "error: permission denied"
echo "info: install dependencies(ffmpeg, curl and lame) or run this scrip as superuser"
exit 1
fi
fi
# check if entered link or given link option a youtube link
while [[ ${link:0:31} != "http://www.youtube.com/watch?v=" && ${2:0:31} != "http://www.youtube.com/watch?v=" ]]; do
echo "enter youtube link:"
read link
done
if [ -z $link ]; then
link=$2
fi
# do you want a mp3 or a mpeg
if [[ $1 = "mp3" || $1 = "mpeg" ]]; then
mediatype=$1
else
while [[ $mediatype != "mp3" && $mediatype != "mpeg" ]]; do
echo 'Do you want an audio or video file? mp3/mpeg[default is mp3].'
read mediatype
if [ -z $mediatype ]; then
mediatype="mp3"
fi
done
fi
# set output destination
if [ -z $3 ];then
destinationpath=$(pwd)
else
destinationpath=$3
fi
# getting flash filename
file=$(ls -l /tmp | grep Flash | awk '{print $8}')
secondfile=$(echo $file | awk '{print $2}')
if [ -z "$file" ]; then
echo "info: there is no open youtube window, trying to start browser"
#chromium-browser $link
firefox $link &
sleep 6
file=$(ls -l /tmp | grep Flash | awk '{print $8}')
secondfile=$(echo $file | awk '{print $2}')
fi
# checking if there is a second flash file in /tmp
if [ -z $secondfile ]; then
i="doitagain"
oldsize=$(ls -l /tmp | grep $file | awk '{print $5}')
sleep 5
while [ $i = "doitagain" ]; do
size=$(ls -l /tmp | grep $file | awk '{print $5}')
if [ $size -gt $oldsize ];then
echo "info: download not finished yet. waiting 5 seconds.."
oldsize=$size
sleep 5
else
echo "info: download finished."
i="goforit"
fi
done
else
echo 'error: there should just be one open video window (if no multiple youtube videos open try "rm -rf /tmp/Flash*")'
exit 1
fi
# parse link for title
curl "$link" --output tmp.txt
rawtitle=$(cat tmp.txt | w3m -dump -T text/html | sed -n '5p')
title=$rawtitle
#rawtitle=$(cat tmp.txt | grep 'meta name="title"')
rm tmp.txt
#count=${#rawtitle}
#length=$(($count-36))
#title=${rawtitle:34:$length}
# here starts the actual convertion
echo "starting convertion of $title @ $link"
if [ $mediatype != "mpeg" ]; then
ffmpeg -i /tmp/$file -vn temp.wav
lame --preset 128 temp.wav "$destinationpath/$title.mp3"
rm temp.wav
title="$title.mp3"
else
ffmpeg -i /tmp/$file -sameq -ab 192k "$destinationpath/$title.mpeg"
title="$title.mpeg"
fi
echo
echo "Output file $destinationpath/$title"
echo
exit 0