Archive for the ‘Bash’ Category.

Vim encryption , encrypting with vim and blowfish.

I am always on the search for the other ways to encrypt my documents on a server.
I’ve used gpg keys, gpg symetric encryption, but this one seems to fit the bill the best.
Encrypting with vim is a very painless process, it does take some setup, but not much, I promise.

The first thing I do is to setup an alias in my .bashrc file.  I alias the following :

alias vime=”vim -u ~/.vimencrypt -x″

vime is short for “vim encrypted”, at least in my head wink
WHEW! Step one finished, that was easy! ……hey, where is that “easy button” again ?

Next is to edit/and or/create a separate .vimrc just for this, and I name mine  .vimencrypt
This file will be in your home directory.  ~/.vimencrypt     
It contains the following:

source ~/.vimrc 
set nobackup 
set noswapfile 
set nowritebackup 
set cm=blowfish

Note: Since Vim 7.3 (2010-08-15)(and newer), vim can now use Blowfish encryption.
If your using an older vim — remove the “set cm=blowfish” line. It will then default to crypt for encryption.

I know, very complicated right ?  wink   That’s it folks, you are now READY to use encryption with vim!
Now, simply type “vime something.txt”  and you’re on your way.

You will then see:

Enter encryption key:

Enter same key again:

If you entered the same key twice, then you should be presented with a normal vim interface.

If you use “vime” to encrypt the document the first time, it will stay encrypted.
You can then just use vim normally to edit it endlessly (vim will ask for your password, you only have to use “vime” on the initial creation of the document), and it’s encrypted when you close it.

Now you will see VimCrypt~02……. when you cat your encrypted file, and it’s encrypted with blowfish, a MUCH MUCH stronger encryption than just “crypt” which can be broken fairly easily.

> cat test VimCrypt~02!sD~wLПYEx

I hope you have fun with vim and encryption.

 

Bash – some .bashrc functions

# bu – A quick backup function

bu () { cp $1 ~/Backups/${1}-`date +%Y%m%d%H%M`.backup ; }

# hs – History Search

hs() {
history | grep ${1} | uniq –skip-fields=1 | sort -biz | uniq –skip-fields=2
}

# stock – Stock information search.

stock ()
{
lynx -dump “http://www.google.com/finance?client=ob&q=${1}” \
| sed ‘s/.*’]’//’ | perl -00ne “print if /Watch this stock/i”  \
| sed ‘s/Watch this stock//’ | sed ‘s/Disclaimer//’  \
| sed ‘/^$/d’ | sed ‘s/Currency in USD//’
}

# smallurl – create a shorter url link.

smallurl ()
{
lynx –dump http://api.fwd4.me/?url=${1}
}

# grepp – Imitate grep -p functions from Tru64 OS.

grepp ()
{
perl -00ne “print if /$1/i” < $2
}

# clock – A stupid clock function

clock ()
{
while true;do clear;echo “===========”;date +”%r”;echo “===========”;sleep 1;done
}

# dirsize – Directory contents sorted by size.

dirsize ()
{
du -shx * .[a-zA-Z0-9_]* 2> /dev/null | \
egrep ‘^ *[0-9.]*[MG]‘ | sort -n > /tmp/list
egrep ‘^ *[0-9.]*M’ /tmp/list
egrep ‘^ *[0-9.]*G’ /tmp/list
rm /tmp/list
}

#extract – Extract most types of compressed files easily

extract ()
{
if [ -f $1 ] ; then
case $1 in
*.tar.bz2)   tar xvf $1     ;;
*.tar.gz)    tar xvf $1     ;;
*.bz2)       bunzip2 $1      ;;
*.rar)       unrar x $1      ;;
*.gz)        gunzip $1       ;;
*.tar)       tar xvf $1      ;;
*.tbz2)      tar xvf $1     ;;
*.tgz)       tar xvf $1     ;;
*.zip)       unzip $1        ;;
*.Z)         uncompress $1   ;;
*.7z)        7z x $1         ;;
*)           echo “‘$1′ cannot be extracted via >extract<” ;;
esac
else
echo “‘$1′ is not a valid file”
fi
}

#############################################################
########### ENCRYPTION / DECRYPTION FUNCTIONS ###############
#############################################################

dc ()
{
# Passphrase decryption program
# Created by Dave Crouse 10-20-2009
# Decrypts symetrically encrypted file to std out.
gpg –no-options –output .tempdc.txt “$1″
cat .tempdc.txt | less; rm -f .tempdc.txt
}

ec ()
{
# Passphrase encryption program
# Created by Dave Crouse 01-13-2006
# Reads input from text editor and encrypts to screen.
clear
echo ” ”
echo “**************************************************”;
echo “*         Passphrase Encryption Program          *”;
echo “**************************************************”; echo “”;
which $EDITOR &>/dev/null
if [ $? != "0" ];
then
echo “It appears that you do not have a text editor set in your
.bashrc file.”;
echo “What editor would you like to use ? ” ;
read EDITOR ; echo “”;
fi
echo “Enter the name/comment for this message :”
read comment
$EDITOR passphraseencryption
gpg –armor –comment “$comment” –no-options –output \

passphraseencryption.gpg –symmetric passphraseencryption
shred -u passphraseencryption ; clear
echo “Outputting passphrase encrypted message”; echo “” ; echo “” ;
cat passphraseencryption.gpg ; echo “” ; echo “” ;
shred -u passphraseencryption.gpg ;
read -p “Hit enter to exit” temp; clear
}

# Passhprase edit encrypted file program
# Created by Dave Crouse 11-02-2009
# Allow editing of symetrically encrypted files.
eedit ()
{
gpg –force-mdc –no-options –output .tempeec $1
emacs .tempeec
#vi .tempeec
gpg –armor –force-mdc –no-options –output $1 –symmetric .tempeec
shred -u .tempeec~ ;shred -u .tempeec ; clear
#shred -u .tempeec
}

enc ()
{
gpg –armor –no-options –output tempenc.txt –symmetric “$1″
mv tempenc.txt “$1″
}

dec ()
{
gpg $1
}

encnotes ()
{
echo “dc = decrpyt to screen”
echo “ec = encrypt to screen”
echo “enc = encrypt file to disk – overwrite existing”
echo “dec = decrypt file to disk – creates new file”
}

Bash Passphrase Encryption to the screen.

Sometimes, I wanted to be able to type a letter, and use a passphrase to encrypt it.
I could then paste the output into an email, forum post, wiki …….whatever and have it unreadable unless someone had the passphrase.

 

 


#!/bin/bash
# Passphrase encryption program
# Created by Dave Crouse 01-13-2006
# Reads input from text editor and encrypts to screen.
clear
echo " Passphrase Encryption Program";
echo "--------------------------------------------------"; echo "";
which $EDITOR &>/dev/null
if [ $? != "0" ];
then
echo "It appears that you do not have a text editor set in your
.bashrc file.";
echo "What editor would you like to use ? " ;
read EDITOR ; echo "";
fi
echo "Enter the name/comment for this message :"
read comment
nano passphraseencryption
gpg --armor --comment "$comment" --no-options --output \
passphraseencryption.gpg --symmetric passphraseencryption
shred -u passphraseencryption ; clear
echo "Outputting passphrase encrypted message"; echo "" ; echo "" ;
cat passphraseencryption.gpg ; echo "" ; echo "" ;
shred -u passphraseencryption.gpg ;
exit

Bash Phone Book Script – Version 2

Phone Book Script – Version 2
This version uses sqlite3 and bash.
Still has things i could fix i suppose …but it works for what i wanted.

I wanted to play with sqlite and bash, so I decided to revamp my older bash phone book script.
And before you ask……. yes, I use this everyday. I work from the command line all day long, and
for me simple is better, console is better than gui, and it did what I wanted it to… thought I’d share
it just in case someone else had this particular itch they needed to scratch.

Yes.. I know the code could be condensed, shortened …whatever, but I prefer “quickly understandable”
vs “obfuscated” code myself…. so knock yerself out if you want too… but I’ll leave that to you.


#!/bin/bash
# Crouse's sqlite+bash phonebook application.
# 11-22-2010 crouse

# Check if requirements are installed.
clear
if [[ -z $( type -p sqlite3 ) ]]; then echo -e "REQUIRED: sqlite3 -- NOT INSTALLED !";exit ;fi

# Check if database already exists, if not, create it.
database="/home/$USER/.phonebook.db"
if [ -e "$database" ];then
echo ""
else
echo "Datase does not exist - Creating now"
sqlite3 $database "create table phonebook (id INTEGER PRIMARY KEY,First TEXT,\
Last TEXT,Street TEXT,City TEXT,State TEXT,Zip TEXT,Phone TEXT,Email TEXT, Notes);"
echo "Database created at $database"
fi

# Check options given to the program and "do stuff".
case ${1} in

# oops--you didn't give me anything
"") echo "Crouse's sqlite+bash phonebook"
echo "================================"
echo "Usage: ${0##*/} ";
echo "";
echo " --------------------"
echo " Create an entry"
echo " $0 -c"
echo " --------------------"
echo " Search by last name \"-l";
echo " -l Smith";
echo "";
echo " Search by phone number";
echo " -p 515-555-5555";
echo ""
echo " Search by email address";
echo " -em EMAIL@SOMEADDRESS";
echo ""
echo " Search by first name with no flags";
echo " $0 dave";
echo " --------------------"
echo " Edit an entry"
echo " $0 -e"
echo "================================"
echo ""
;;

# Create an entry
"-c")
clear
echo "Phone Book - Insert data into database"
echo "--------------------------------------"
echo "FORMAT: First Name,Last Name,Street,City,State,Zip,Phone,Email,Notes"
echo " "

#Insert data into database
read -p "First Name: " First
read -p " Last Name: " Last
read -p " Street: " Street
read -p " City: " City
read -p " State: " State
read -p " Zip: " Zip
read -p " Phone: " Phone
read -p " Email: " Email
read -p " Notes: " Notes

sqlite3 $database "insert into phonebook (First,Last,Street,City,State,Zip,Phone,Email,Notes) \
values ('$First','$Last','$Street','$City','$State','$Zip','$Phone','$Email','$Notes');"

#clear
echo "-----------------------------"
echo "Data Entered into Database"
;;

# Edit an entry
"-e")
clear
read -p "Enter id# to edit: " idnum
echo ""

sqlite3 $database<<EOF
.header off
.mode line
select id,First,Last,Street,City,State,Zip,Phone,Email,Notes from phonebook \
WHERE id = '${idnum}';
.quit
EOF

echo ""
echo "Hitting enter will just leave that line as is."
echo ""
echo "-----------------------------------------------"
#Insert data into database
read -p "First Name: " First
read -p " Last Name: " Last
read -p " Street: " Street
read -p " City: " City
read -p " State: " State
read -p " Zip: " Zip
read -p " Phone: " Phone
read -p " Email: " Email
read -p " Notes: " Notes

echo ""

if [[ "$First" != "" ]]; then
sqlite3 $database "UPDATE phonebook SET First = '${First}' WHERE id='${idnum}';"
fi

if [[ "$Last" != "" ]]; then
sqlite3 $database "UPDATE phonebook SET Last = '${Last}' WHERE id='${idnum}';"
fi

if [[ "$Street" != "" ]]; then
sqlite3 $database "UPDATE phonebook SET Street = '${Street}' WHERE id='${idnum}';"
fi

if [[ "$City" != "" ]]; then
sqlite3 $database "UPDATE phonebook SET City = '${City}' WHERE id='${idnum}';"
fi

if [[ "$State" != "" ]]; then
sqlite3 $database "UPDATE phonebook SET State = '${State}' WHERE id='${idnum}';"
fi

if [[ "$Zip" != "" ]]; then
sqlite3 $database "UPDATE phonebook SET Zip = '${Zip}' WHERE id='${idnum}';"
fi

if [[ "$Phone" != "" ]]; then
sqlite3 $database "UPDATE phonebook SET Phone = '${Phone}' WHERE id='${idnum}';"
fi

if [[ "$Email" != "" ]]; then
sqlite3 $database "UPDATE phonebook SET Email = '${Email}' WHERE id='${idnum}';"
fi

if [[ "$Notes" != "" ]]; then
sqlite3 $database "UPDATE phonebook SET Notes = '${Notes}' WHERE id='${idnum}';"
fi
;;

# Search by last name
"-l")
echo ""
sqlite3 $database<<EOF
.header off
.mode line
select id,First,Last,Street,City,State,Zip,Phone,Email,Notes from phonebook \
WHERE Last LIKE '%${2}%';
.quit
EOF
;;

# Search by phone
"-p")
echo ""
sqlite3 $database<<EOF
.header off
.mode line
select id,First,Last,Street,City,State,Zip,Phone,Email,Notes from phonebook \
WHERE Phone LIKE '%${2}%';
.quit
EOF
;;

# Search by email
"-em")
echo ""
sqlite3 $database<<EOF
.header off
.mode line
select id,First,Last,Street,City,State,Zip,Phone,Email,Notes from phonebook \
WHERE Email LIKE '%${2}%';
.quit
EOF
;;

# Search by first name for all others
*)
echo "";
sqlite3 $database<<EOF
.header off
.mode line
select id,First,Last,Street,City,State,Zip,Phone,Email,Notes from phonebook \
WHERE First LIKE '%${1}%';
.quit
EOF
;;

esac
echo ""
exit 0


Crouse’s sqlite+bash phonebook
================================
Usage: pb

——————–
Create an entry
/usr/local/bin/pb -c
——————–
Search by last name “-l
-l Smith

Search by phone number
-p 515-555-5555

Search by email address
-em xxxxx@usalug.net

Search by first name with no flags
/usr/local/bin/pb dave
——————–
Edit an entry
/usr/local/bin/pb -e
================================

screenhelp – show notes about screen.

This isn’t so much a script as it is some helpful notes on running screen.
When people are learning to use screen, it can be daunting, so I created some notes that people could use to quickly find out how to do X. Thought I’d share. :)
Continue reading ‘screenhelp – show notes about screen.’ »

Bash – mysql backup script

This script backs up all databases on the server it’s running on. Usually ran as a cron job.

Hope someone else can use this as well.

#!/bin/bash
# Backup ALL mysql databases
# by crouse - http://archlinux.me/crouse
x=`mysql --user=root --password=REMOVED -B -e "show databases"  | wc -l `; y=$((x-2));
for i in `mysql --user=root --password=REMOVED -B -e "show databases"  | tail -${y}`; do
mysqldump --opt --user=root --password=REMOVED $i | gzip -9 > /root/MYSQLBACKUPS/$i.`date --iso-8601`-mysqlbackup.gz
ls -t /root/MYSQLBACKUPS/$i.* | awk 'NR>7' | xargs rm -f
done
# Mail updates
touch sendthis
echo "" > sendthis
echo "Archlinux.me Nightly Mysql Backup Information" >> sendthis
echo "---------------------------------------------" >> sendthis
echo " " >> sendthis
ls -la /root/MYSQLBACKUPS/ >> sendthis
cat sendthis | mail -s mail SOMEEMAIL@archlinux.us -s "Archlinux.me - Nightly Mysql Backup Notice"
rm sendthis
exit

sendenc – Send an encrypted email from the shell.

This script requires that you have a mail server configured on the machine your running it from.
#!/bin/bash
# Date: 03-18-2010
# Created by Dave Crouse

# Filename: sendencrypted
# Usage: sendencrypted
# Notes: Interactive- send passphrase encrypted email.

clear
echo "Send Passphrase Encrypted Email."
echo "------------------------------------------------"
read -p " Enter your email address: " replyto
read -p " Enter the email address you are sending to: " name
read -p " Enter the subject line of your email: " subject
echo "Enter the name/comment to put on the encrypted message. \
Just hit enter if you don't want any comments on it."
read -p "Note, this will be in clear text and readable by anyone! : " comment;
read -p "Hit ENTER to open vi and create your email." temp;

vi passphraseencryption
gpg --armor --comment "$comment" --no-options --output \
passphraseencryption.gpg --symmetric passphraseencryption
shred -u passphraseencryption

from="${replyto}"
emailthis=`cat passphraseencryption.gpg`

cat <<EOF | /usr/sbin/sendmail -f noreply -t
to:${name}
from:${from}
reply-to:${replyto}
subject: ENCRYPTED-${subject}
content-type: text/plain
${emailthis}
EOF

shred -u passphraseencryption.gpg
exit 0

Bash Server Ping Checking Script

# Pretty simple, add servers/ip’s/Ln (line numbers) in the format shown in the two column examples.
# Tested with over 50 servers, worked for what I needed, thought i’d share :)


#!/bin/bash
# Bash Server Ping Checking -written by Dave Crouse
# 09-24-2009 Crouse
# Pretty simple, add servers/ip's/Ln (line numbers) in the format shown in the two column examples.
# Tested with over 50 servers, worked for what I needed, thought i'd share :) ~~Crouse.

# Ideas --- ad another array for Headers. so Hn could print headers with bold/etc. Might be neat.
declare -a Sn # Server Name
declare -a Ip # IP address of server.
declare -a Ln # Line number to display on in Row1.
declare -a Sn2 # Server Name
declare -a Ip2 # IP address of server.
declare -a Ln2 # Line number to display on in Row2.
############################################################################### Server List Row 1
###############################################################################
Sn[1]="usalug.org"
Ip[1]="67.15.6.98"
Ln[1]="6"

Sn[2]="archlinux.me"
Ip[2]="208.92.232.122"
Ln[2]="7"
###############################################################################
###############################################################################

############################################################################### Server List Row 2
###############################################################################
Sn2[1]="usalug.org"
Ip2[1]="67.15.6.98"
Ln2[1]="6"

Sn2[2]="archlinux.me"
Ip2[2]="208.92.232.122"
Ln2[2]="7"
################################################################################
################################################################################
tput civis # Hide the cursor
maxcount=${#Sn[*]} #should report number of Servers listed in Sn variable
maxcount2=${#Sn2[*]} #should report number of Servers listed in Sn2 varialbe
clear
#tput setf 2; #echo -e '\e[1;33m'
echo " "
tput setf 0;tput setb 2;
echo " Bash Server Ping Checking Utility version 2.0 Crouse. "; #tput rmso;

tput setf 7; tput setb 0; # List out servers now.
for (( loop=1; $loop < $maxcount+1; loop++ ))
do
( tput cup ${Ln[$loop]} 10; echo "${Sn[$loop]}"; tput rc)
done
for (( loop2=1; $loop2 < $maxcount2+1; loop2++ ))
do
( tput cup ${Ln2[$loop2]} 50; echo "${Sn[$loop2]}"; tput rc)
done
# Set traps so when we exit the big ass loop stuffs normal again.
gracefulexit () {
tput cnorm;
tput setb 0;
echo "Stopping Application"
tput setf 2;
exit
}
trap gracefulexit INT TERM EXIT
# Begin big ass loop
while true
do
#First Row
for (( loop=1; $loop < $maxcount+1; loop++ ))
do
(tput sc ;tput setb 0; tput setf 0; tput cup 4 10 ;
echo "........................................................................";tput rc)
(tput sc ;tput setb 0; tput setf 6; tput cup 4 10 ;
echo "Checking ${Sn[$loop]} at IP: ${Ip[$loop]}" ; tput rc)
(tput sc ;tput setb 0; tput setf 0; tput cup ${Ln[$loop]} 1 ; echo "........." ; tput rc)
(tput sc ;tput setb 0; tput setf 6; tput cup ${Ln[$loop]} 1 ; echo "TESTING" ; tput rc)
count=$(ping -c 5 ${Ip[$loop]} | grep 'received' | awk -F',' '{ print $2 }' | awk '{ print $1 }')
(tput sc ;tput setb 0; tput setf 0; tput cup ${Ln[$loop]} 1 ; echo "........." ; tput rc)
if [[ "$count" == [45] ]]; then
(tput sc ;tput setf 0; tput setb 2;tput cup ${Ln[$loop]} 5 ; echo " OK " ; tput rc)
else
if [[ "$count" == [123] ]]; then
(tput sc ;tput setf 0; tput setb 6; tput cup ${Ln[$loop]} 4 ; echo "ALERT" ; tput rc)
else
(tput sc ;tput setf 7; tput setb 4; tput cup ${Ln[$loop]} 2 ; echo "WARNING" ; tput rc)
fi
fi
done
#Second Row
for (( loop2=1; $loop2 < $maxcount2+1; loop2++ ))
do
(tput sc ;tput setb 0; tput setf 0; tput cup 4 10 ;
echo "........................................................................";tput rc)
(tput sc ;tput setb 0; tput setf 6; tput cup 4 10 ;
echo "Checking ${Sn2[$loop2]} at IP: ${Ip2[$loop2]}" ; tput rc)
(tput sc ;tput setb 0; tput setf 0; tput cup ${Ln2[$loop2]} 41 ; echo "........." ; tput rc)
(tput sc ;tput setb 0; tput setf 6; tput cup ${Ln2[$loop2]} 41 ; echo "TESTING" ; tput rc)
count2=$(ping -c 5 ${Ip2[$loop2]} | grep 'received' | awk -F',' '{ print $2 }' | awk '{ print $1 }')
(tput sc ;tput setb 0; tput setf 0; tput cup ${Ln2[$loop2]} 41 ; echo "........." ; tput rc)
if [[ "$count2" == [45] ]]; then
(tput sc ;tput setf 0; tput setb 2;tput cup ${Ln2[$loop2]} 45 ; echo " OK " ; tput rc)
else
if [[ "$count2" == [123] ]]; then
(tput sc ;tput setf 0; tput setb 6; tput cup ${Ln2[$loop2]} 44 ; echo "ALERT" ; tput rc)
else
(tput sc ;tput setf 7; tput setb 4; tput cup ${Ln2[$loop2]} 42 ; echo "WARNING" ; tput rc)
fi
fi
done
done

Bash – a quick stock quote function

Wrote this and stuck it in my .bashrc file so I could get a realtime stock quote quickly from my shell sessions.

stock ()
{
lynx -dump "http://www.google.com/finance?client=ob&amp;q=${1}" | sed 's/.*']'//' | \
perl -00ne "print if /Watch this stock/i" | sed 's/Watch this stock//' | sed 's/Disclaimer//' | \
sed '/^$/d' | sed 's/Currency in USD//'
}

crouse@archie stock slv

slv
30.26
+0.08 (0.27%)
Real-time: 11:41AM EST

1. Range 30.14 – 30.44
2. 52 week 14.37 – 30.44
3. Open 30.29
4. Vol / Avg. 9.57M/26.84M
5. Mkt cap 9.73B
6. P/E 95.32
7. Div/yield -
8. EPS 0.32
9. Shares 321.50M
10. Beta 0.38
11. Inst. own 25%

TIP: Ever get those strange characters in your console ?

Ever get those strange looking little buggers in your console after installing Arch and firing up the terminal ?
Something like this –
[crouse@archie ~]$ pstree
init─┬─6*[agetty]
├─crond
├─httpd───11*[httpd]
├─mysqld_safe───mysqld───9*[{mysqld}]
├─sshd─┬─sshd───sshd───bash───su───bash
│ └─sshd───sshd───bash───pstree
├─syslog-ng───syslog-ng
├─udevd───udevd
└─vmtoolsd

Simply add the following to your .bashrc and close your terminal window and open it up again, or source the .bashrc file again.
export LC_ALL=C

[crouse@archie ~]$ pstree
init-+-6*[agetty]
|-crond
|-httpd---11*[httpd]
|-mysqld_safe---mysqld---9*[{mysqld}]
|-sshd-+-sshd---sshd---bash---su---bash
| `-sshd---sshd---bash---pstree
|-syslog-ng---syslog-ng
|-udevd---udevd
`-vmtoolsd
[crouse@archie ~]$