Search This Blog
Wednesday, October 17, 2012
Saturday, October 06, 2012
Remove weird characters from filenames
paste <(find . -print | awk '{print "\042"$0"\042"}') <(find . -print | sed -e 's/\o300/A/g' -e 's/\o301/A/g' -e 's/\o302/A/g' -e 's/\o340/a/g' -e 's/\o341/a/g' -e 's/\o342/a/g' -e 's/\o307/C/g' -e 's/\o347/c/g' -e 's/\o310/E/g' -e 's/\o311/E/g' -e 's/\o312/E/g' -e 's/\o350/e/g' -e 's/\o351/e/g' -e 's/\o352/e/g' -e 's/\o316/I/g' -e 's/\o356/i/g' -e 's/\o322/O/g' -e 's/\o323/O/g' -e 's/\o324/O/g' -e 's/\o362/o/g' -e 's/\o363/o/g' -e 's/\o364/o/g' -e 's/\o331/N/g' -e 's/\o361/n/g' -e 's/\o331/U/g' -e 's/\o332/U/g' -e 's/\o333/U/g' -e 's/\o371/u/g' -e 's/\o372/u/g' -e 's/\o373/u/g' -e 's/\o357/i/g' -e 's/\o317/I/g' -e 's/\o264/_/g' -e 's/\o250/_/g' -e 's/[)(]/-/g' -e 's/^\(.*\)$/"\1"/') | sed -e 's/^/mv /'
pretty neat, heh?
I'm using awk when I define the source because sed -e 's/.*/"&"/' or 's/^\(.*\)$/"\1"/' fails in the weird characters.
And while being there, find . -type f -regextype posix-extended ! -iregex '.*.(mp3|avi|mkv|wmv|mp4|mp5|flv|M4V|mpeg|mov|m1v|m2v|3gp|avchd)$' -delete will nicely clean up the music folders :)
the characters definitions are found in /usr/share/X11/locale/iso8859-1/Compose
Monday, September 17, 2012
Clear Win7 UserProfile
' Clear Win7/Win2008 User Profile and registry
' to be executed on each Terminal Server
'(c)2012-2014 sorinakis@gmail
Set WshShell = CreateObject("WScript.Shell")
Set WshNet = WScript.CreateObject("WScript.Network")
Set WMIService = GetObject("winmgmts:\\.\root\cimv2")
Set objRegistry = GetObject("winmgmts:\\.\root\default:StdRegProv")
set WshFSO = CreateObject("Scripting.FileSystemObject")
const HKEY_LOCAL_MACHINE = &H80000002
dim strUser
Do
strUser = InputBox(vbCrLf & "Please enter the username you wish to reset: ", "Profile Cleaner")
If TypeName(strUser) = "Empty" Then
WScript.Quit
End If
If Len(Trim(strUser)) = 0 Then
MsgBox "You have to Enter Username To Reset",48
End If
Loop While Len(Trim(strUser)) = 0
'' debug
'with createobject("wscript.shell")
'.popup "User: " & strUser , 5 , "Info"
'end with
'' end debug
if CStr(CheckUser(strUser)) then
Set Account = WMIService.Get("Win32_UserAccount.Name='" & strUser & "',Domain='" & WshNet.UserDomain & "'")
strRegKey = "SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\" + Account.SID
if CheckRegKey(strRegKey) then
strUserProfile = WshShell.ExpandEnvironmentStrings(WshShell.RegRead("HKEY_LOCAL_MACHINE\" + strRegKey + "\ProfileImagePath"))
strRmtFldr = WshShell.ExpandEnvironmentStrings(WshShell.RegRead("HKEY_LOCAL_MACHINE\" + strRegKey + "\CentralProfile"))
Else
MsgBox " The registry key for user " & strUser & " does not exist! Can NOT backup and clean anything!" & vbCrLf & vbCrLf & "Please manually check for and rename the USERPROFILE and ROAMINGPROFILE Folders.",16
wscript.quit
End If
strRegFile = strUserProfile & "\reg_backup.reg"
regCmd = "regedit.exe /E """ & strRegFile & """ " & """HKEY_LOCAL_MACHINE\" & strregKey & """"
If WshFSO.FolderExists (strUserProfile) Then
'' debug
'with createobject("wscript.shell")
'.popup "Backup: " & strUserProfile , 5 , "Info"
'end with
'' end debug
WshShell.Run regCmd, 0, True
WshFSO.MoveFolder strUserProfile , strUserProfile & ".backup"
End If
If WshFSO.FolderExists (strRmtFldr) Then
'' debug
'with createobject("wscript.shell")
'.popup "Backup: " & strRmtFldr , 5 , "Info"
'end with
'' end debug
WshFSO.MoveFolder strRmtFldr , strRmtFldr & ".backup"
End If
'' debug
'with createobject("wscript.shell")
'.popup "Removing: HKEY_LOCAL_MACHINE\" & strRegKey , 5 , "Info"
'end with
'' end debug
DeleteSubkeys HKEY_LOCAL_MACHINE, strRegKey
Sub DeleteSubkeys(HKEY_LOCAL_MACHINE, strRegKey)
objRegistry.EnumKey HKEY_LOCAL_MACHINE, strRegKey, arrSubkeys
If IsArray(arrSubkeys) Then
For Each strSubkey In arrSubkeys
DeleteSubkeys HKEY_LOCAL_MACHINE, strRegKey & "\" & strSubkey
Next
End If
objRegistry.DeleteKey HKEY_LOCAL_MACHINE, strRegKey
End Sub
' Open the backed up profile it in explorer...
'strPath = "explorer.exe /e, strRmtFldr" & ".backup"
'WshShell.Run strPath
'debug
with createobject("wscript.shell")
.popup "Profile of " & strUser & " has been processed.", 5 , "Info"
end with
'' end debug
wscript.quit
Else
MsgBox "USER " & strUser & " NOT FOUND!", 16
wscript.quit
End If
Function CheckRegKey(strRegKey)
On Error Resume next
strUserProfile = WshShell.ExpandEnvironmentStrings(WshShell.RegRead("HKEY_LOCAL_MACHINE\" + strRegKey + "\ProfileImagePath"))
If Err.Number <> 0 Then
Err.Clear
CheckRegKey = false
else
Err.Clear
CheckRegKey = true
End If
end function
Function CheckUser(user)
On Error Resume next
with CreateObject("WScript.Shell")
Set Account = WMIService.Get("Win32_UserAccount.Name='" & User & "',Domain='" & WshNet.UserDomain & "'")
end with
CheckUser = (Err.Number = 0)
On Error Goto 0
end function
' to be executed on each Terminal Server
'(c)2012-2014 sorinakis@gmail
Set WshShell = CreateObject("WScript.Shell")
Set WshNet = WScript.CreateObject("WScript.Network")
Set WMIService = GetObject("winmgmts:\\.\root\cimv2")
Set objRegistry = GetObject("winmgmts:\\.\root\default:StdRegProv")
set WshFSO = CreateObject("Scripting.FileSystemObject")
const HKEY_LOCAL_MACHINE = &H80000002
dim strUser
Do
strUser = InputBox(vbCrLf & "Please enter the username you wish to reset: ", "Profile Cleaner")
If TypeName(strUser) = "Empty" Then
WScript.Quit
End If
If Len(Trim(strUser)) = 0 Then
MsgBox "You have to Enter Username To Reset",48
End If
Loop While Len(Trim(strUser)) = 0
'' debug
'with createobject("wscript.shell")
'.popup "User: " & strUser , 5 , "Info"
'end with
'' end debug
if CStr(CheckUser(strUser)) then
Set Account = WMIService.Get("Win32_UserAccount.Name='" & strUser & "',Domain='" & WshNet.UserDomain & "'")
strRegKey = "SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\" + Account.SID
if CheckRegKey(strRegKey) then
strUserProfile = WshShell.ExpandEnvironmentStrings(WshShell.RegRead("HKEY_LOCAL_MACHINE\" + strRegKey + "\ProfileImagePath"))
strRmtFldr = WshShell.ExpandEnvironmentStrings(WshShell.RegRead("HKEY_LOCAL_MACHINE\" + strRegKey + "\CentralProfile"))
Else
MsgBox " The registry key for user " & strUser & " does not exist! Can NOT backup and clean anything!" & vbCrLf & vbCrLf & "Please manually check for and rename the USERPROFILE and ROAMINGPROFILE Folders.",16
wscript.quit
End If
strRegFile = strUserProfile & "\reg_backup.reg"
regCmd = "regedit.exe /E """ & strRegFile & """ " & """HKEY_LOCAL_MACHINE\" & strregKey & """"
If WshFSO.FolderExists (strUserProfile) Then
'' debug
'with createobject("wscript.shell")
'.popup "Backup: " & strUserProfile , 5 , "Info"
'end with
'' end debug
WshShell.Run regCmd, 0, True
WshFSO.MoveFolder strUserProfile , strUserProfile & ".backup"
End If
If WshFSO.FolderExists (strRmtFldr) Then
'' debug
'with createobject("wscript.shell")
'.popup "Backup: " & strRmtFldr , 5 , "Info"
'end with
'' end debug
WshFSO.MoveFolder strRmtFldr , strRmtFldr & ".backup"
End If
'' debug
'with createobject("wscript.shell")
'.popup "Removing: HKEY_LOCAL_MACHINE\" & strRegKey , 5 , "Info"
'end with
'' end debug
DeleteSubkeys HKEY_LOCAL_MACHINE, strRegKey
Sub DeleteSubkeys(HKEY_LOCAL_MACHINE, strRegKey)
objRegistry.EnumKey HKEY_LOCAL_MACHINE, strRegKey, arrSubkeys
If IsArray(arrSubkeys) Then
For Each strSubkey In arrSubkeys
DeleteSubkeys HKEY_LOCAL_MACHINE, strRegKey & "\" & strSubkey
Next
End If
objRegistry.DeleteKey HKEY_LOCAL_MACHINE, strRegKey
End Sub
' Open the backed up profile it in explorer...
'strPath = "explorer.exe /e, strRmtFldr" & ".backup"
'WshShell.Run strPath
'debug
with createobject("wscript.shell")
.popup "Profile of " & strUser & " has been processed.", 5 , "Info"
end with
'' end debug
wscript.quit
Else
MsgBox "USER " & strUser & " NOT FOUND!", 16
wscript.quit
End If
Function CheckRegKey(strRegKey)
On Error Resume next
strUserProfile = WshShell.ExpandEnvironmentStrings(WshShell.RegRead("HKEY_LOCAL_MACHINE\" + strRegKey + "\ProfileImagePath"))
If Err.Number <> 0 Then
Err.Clear
CheckRegKey = false
else
Err.Clear
CheckRegKey = true
End If
end function
Function CheckUser(user)
On Error Resume next
with CreateObject("WScript.Shell")
Set Account = WMIService.Get("Win32_UserAccount.Name='" & User & "',Domain='" & WshNet.UserDomain & "'")
end with
CheckUser = (Err.Number = 0)
On Error Goto 0
end function
Friday, April 06, 2012
Cyclic paging script
Let's say that we have an emergency voicemail box where our clients can leave us messages if they have a contract for extended hours or a limited response time contract. Let's also suppose that we have a shitty mobile phone provider, whose signal does no goes higher that 3000ft and is not available too far in wilderness, but we still have those old pagers, able to receive the signal even on top of mount Everest. And let's say that we have a bunch of unfortunate enough bastards on call that are supposed to respond to those calls. Now, every week it's some other poor bastard turn to be on call, but just in case he's not available, we might be force to page the other unfortunates, even when it is not their week of duty. And we page them in order, one after another, until one of them login the web interface of our asterisk server or call the emergency mailbox and acknowledge the message.
This is the script that have to be run from cron every */10 minutes on the asterisk server:
#!/bin/bash
# A script that checks for new messages on emergency voicemail and send messages to pagers
# (c) 2012 sorin@xxxxxxxx.com under the terms of GNU GPL
#
# 2012/06/23 v0.5 neXt (sorin@xxxxxxxx.com) - Add names to email
# 2012/06/09 v0.4 neXt (sorin@xxxxxxxx.com) - Don't send pages during the night
# 2012/05/10 v0.3 neXt (sorin@xxxxxxxx.com) - Monday morning warn the user on duty
# 2012/04/09 v0.2 neXt (sorin@xxxxxxxx.com) - Verify if the cycle has been done today
# 2012/04/06 v0.1 neXt (sorin@xxxxxxxx.com) - Initial release
# Voicemail location
voicemail=/var/spool/asterisk/voicemail/default/911/INBOX/
# Paging provider
provider=paging.xxxxxxxx.com
# Working directory
working=/var/emergency
if [ ! -d $working ] ; then
mkdir -p $working
fi
# Location of the file containing the pager numbers
pagers=$working/pager_numbers
if [ ! -f $pagers ] ; then
# If the pager file does not exist define the defaults - We need a NEW-LINE at the end of the file!
echo "5140000000 John Doe john@xxxxxxxx.com
5140000001 Jane Doe jane@xxxxxxxx.com
5140000002 Jack Doe jack@xxxxxxxx.com
" > $pagers
fi
# A temporary file containing a volatile data
runvars=$working/tmpvars
if [ ! -f $runvars ] ; then
# If the variables file does not exist define some sane defaults
echo "current=1" > $runvars
echo "oldday=0" > $runvars
fi
# Cycle pager numbers every Monday, the first number will become the last
today=`date +%w`
day=`date +%d%m`
# read the variables
. $runvars 1>&2>/dev/null
# If today is Monday (weekday 1) and the numbers were not already cycled
if [ $today = 1 ] && [ ! $day = $oldday ]; then
# copy pager numbers to a new file, deleting the first line of this file
sed -n "2,\$ p;/^ *$/d" $pagers > $pagers.new
# read the first line of the old file and put that line at the end of the new file
head -1 $pagers >> $pagers.new
# replace the old file with the new one
mv -f $pagers.new $pagers
# send an email with the name and number of the current guy on duty
guy=`head -n1 $pagers | tail -n1
recipients=`cat $pagers | sed 's/[^@]* \([a-zA-Z0-9.]*@[^ ]*\).*/\1/' | sed ':a;N;$!ba;s/\n/ /g'`
echo "This week the main pager is $guy" | mail -s "Pager $guy" $recipients
# page this new guy with a test message, but not in the middle of the night, 07:30AM seems like OK-ish...
guynr=`echo "$guy" | cut -f1 -d" "`
wrn="echo '00 10-86 00' | mail -s911 $guynr@$provider"
echo $wrn | at 07:30
# keep the today's date into variable oldday - used to see if we've already processed the cycle today
sed -i "/oldday/d" $runvars
echo "oldday=$day" >> $runvars
fi
# We DO NOT send paging messages between 10PM and 7AM - there are no contracts between those hours
if [ $((10#$(date +%H%M))) -gt 700 ] && [ $((10#$(date +%H%M))) -lt 2200 ]; then
# Let's see if there are new messages in the emergency voicemail
messages=`ls -l $voicemail | wc -l`
if [ $messages -gt 1 ]; then
# There is something in the voicemail, read the already defined variables to see to whom we have to send the page
. $runvars 1>&2>/dev/null
# If we are aleady at the end of the paging list, we have to restart from the beginning and annoy everybody again
max_current=`wc -l $pagers | cut -f1 -d" "`
if [ $current -gt $max_current ]; then
current=1
fi
# Hell, let's send a page to the sucker that is on duty today. Extract only the phone number from file.
current_page=`head -n$current $pagers | tail -n1 | cut -f1 -d" "`
# echo "msg=$messages max=$max_current cn=$current cur=$current_page" # This line is here for debugging
echo "10-78 911" | mail -s911 $current_page@$provider
# Now remember, we've already sent a page to this unfortunate, if he's not available, we'll have to move to the next in line
current=`expr $current + 1`
sed -i "/current/d" $runvars
echo "current=$current" >> $runvars
else
# Cleanup the variables, some poor bastard took the message, we reset the counter
sed -i "/current/d" $runvars
echo "current=1" >> $runvars
fi
fi
---------------------------------------------------------------------------------------------
Note: This is work in progress. I'll update changes during time.
Sunday, November 06, 2011
IP Changing notification
Because sometimes the dyndns updater goes to hell, a little crontab script executed every couple of hours it's a life saver:
#!/bin/sh
#
# Send an email message to notify about the external IP.
#
#set a file where we can store the ip
logfile=/var/log/extip
#to whom we send the email
recipient="my_account@provider.tld"
#if we are using an external smtp relay
smtp=relay.smtp.provider.tld
export smtp=$smtp
#put a nice sender address on the email
sender="IP Checker<ipcheck@server.tld>"
#find the name of of this server
HOSTNAME=`hostname -a | cut -f1 -d" "`
# format a nice subject
subj="Change of IP on $HOSTNAME"
#now let's get the external ip
ip=`/usr/bin/lynx -dump 'http://whatismyip.org'`
#and create a message body
mesg="$HOSTNAME IP address on `date +%a' '%b' '%e' '%H.%M.%S' '%Z' '%Y` is $ip"
#see if the ip has changed
oldip=`cat $logfile`
#or if the last message has been sent more than one week ago
age=`find $logfile -mtime +7`
if [ ! "$oldip" == "$ip" ] || [ ! "$age" == "" ]
then
#keep the new ip into the logfile
echo $ip > $logfile
#send email about it
echo "$mesg" | mail -r"$sender" -s"$subj" "$recipient"
fi
exit 0
Of course, having an external web server, capable of running a little php script will allow us to replace http://whatismyip.org with our own webserver. The php script is really simple:
#!/bin/sh
#
# Send an email message to notify about the external IP.
#
#set a file where we can store the ip
logfile=/var/log/extip
#to whom we send the email
recipient="my_account@provider.tld"
#if we are using an external smtp relay
smtp=relay.smtp.provider.tld
export smtp=$smtp
#put a nice sender address on the email
sender="IP Checker
#find the name of of this server
HOSTNAME=`hostname -a | cut -f1 -d" "`
# format a nice subject
subj="Change of IP on $HOSTNAME"
#now let's get the external ip
ip=`/usr/bin/lynx -dump 'http://whatismyip.org'`
#and create a message body
mesg="$HOSTNAME IP address on `date +%a' '%b' '%e' '%H.%M.%S' '%Z' '%Y` is $ip"
#see if the ip has changed
oldip=`cat $logfile`
#or if the last message has been sent more than one week ago
age=`find $logfile -mtime +7`
if [ ! "$oldip" == "$ip" ] || [ ! "$age" == "" ]
then
#keep the new ip into the logfile
echo $ip > $logfile
#send email about it
echo "$mesg" | mail -r"$sender" -s"$subj" "$recipient"
fi
exit 0
Of course, having an external web server, capable of running a little php script will allow us to replace http://whatismyip.org with our own webserver. The php script is really simple:
<?php
$ip = getenv('REMOTE_ADDR');
#$ip = $_SERVER['REMOTE_ADDR'];
echo '
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
' . $ip . '
</body>
</html>';
?>
Sunday, October 16, 2011
Sunday, August 07, 2011
AUTOTBACK 3.0
A new version of the backup utility.
This is an evolution of the old AUTOTBACK script.
If the script is called without any command-line parameters it will check if "dialog" is installed on the system and it will start the "semi-graphical" interface, otherwise it will display the "usage parameters" and it will exit.
The command line parameters are still the same:
$autotback ACTION DIRECTORY ARCHIVE MAIL PRINTER, where
- ACTION is backup or restore
- DIRECTORY represent, in case of ACTION=backup the source (what we will backup), or the destination (where the backup will be restored) when ACTION=restore. The default value is "/".
- ARCHIVE represent the location of backup. It is usually the tape device (by default is /dev/st0), but it can also be a simple file (/mnt/disk/archive_name.cpio - if we use an external drive mounted on /mnt/disk)
- MAIL represent the email address(es) that will receive the backup report. If more than one email address is required, then, on the command line, those must be surrounded by double quotes ("aa@bb.c dd@ee.f gg@hh.i"). The default emails are "backupreport@xxxxxxxx.com root@localhost"
-PRINTER represents the name of the printer used for the report. The default value is empty. The printer MUST be already installed on the system!
This is an evolution of the old AUTOTBACK script.
If the script is called without any command-line parameters it will check if "dialog" is installed on the system and it will start the "semi-graphical" interface, otherwise it will display the "usage parameters" and it will exit.
The command line parameters are still the same:
$autotback ACTION DIRECTORY ARCHIVE MAIL PRINTER, where
- ACTION is backup or restore
- DIRECTORY represent, in case of ACTION=backup the source (what we will backup), or the destination (where the backup will be restored) when ACTION=restore. The default value is "/".
- ARCHIVE represent the location of backup. It is usually the tape device (by default is /dev/st0), but it can also be a simple file (/mnt/disk/archive_name.cpio - if we use an external drive mounted on /mnt/disk)
- MAIL represent the email address(es) that will receive the backup report. If more than one email address is required, then, on the command line, those must be surrounded by double quotes ("aa@bb.c dd@ee.f gg@hh.i"). The default emails are "backupreport@xxxxxxxx.com root@localhost"
-PRINTER represents the name of the printer used for the report. The default value is empty. The printer MUST be already installed on the system!
#!/bin/sh
# @(#) AUTOTBACK 3.4 08/09/12
#
# 08/06/2012 (sorin@xxxxxxxx.com) add pre/post actions, embedd dialog
# 17/10/2011 (sorin@xxxxxxxx.com) modify to use tar
# 18/07/2011 (sorin@xxxxxxxx.com) add the restore section, add command-line parmeters
# 10/08/2010 (sorin@xxxxxxxx.com) autoremove lock after 8hrs and reenable backup. remove hit report
# 28/08/2008 (sorin@xxxxxxxx.com) modified for rhel5. skip /proc /sys /tmp. send mail with the result
# modified 9/14/2000 to provide hit reporting on web site
#
# Usage: $0 backup /source /dev/destination email@notification.address (printer)
# if no source nor destination is provided, / will be saved to /dev/st0
# $0 restore /destination /dev/source email@notification.address (printer)
# when restore is called, the script will ask you to select a partial restore
# by typing a file mask. Just type Enter to do a full restore.
# if no destination is provided, the restore is performed on / from /dev/st0
# All the reports and temp files are kept in the /var/autotback directory
#
#
# Exit Codes: 0 - OK
# 1 - [ESC] pressed
# 2 - A lockfile exists
# 3 - Can't create dir (am I root? is it /var mounted rw?)
#
#
# If not provided on the commandline, set local Variables. Must specify at least the main action (backup/restore)
unset SRC DES REC PRN
#if [ "$1" = "" ]; then echo "Usage: $0 {backup|restore} (files) (archive) (email) (printer)"; fi # if dialog exists start anyway
if [ ! "$2" = "" ]; then SRC=$2; else SRC=/; fi
if [ ! "$3" = "" ]; then DES=$3; else DES=/dev/st0; fi
if [ ! "$4" = "" ]; then REC=$4; else REC="backupreport@xxxxxxxx.com root@localhost"; fi
if [ ! "$5" = "" ]; then PRN=$5; fi
# System variables
#PRECOMMAND='/bin/mount -t cifs -o guest //192.168.1.16/images /mnt'
#POSTCOMMAND='/bin/umount /mnt'
ARCHIVER=tar
DEFAULTDIR=/var/autotback
LOCK=$DEFAULTDIR/backlock
REPORTFILE=$DEFAULTDIR/backrep$$
TEMPFILE=$DEFAULTDIR/backtmp$$
TEMPFILE2=$DEFAULTDIR/backtemp$$
TEMPFILEV=$DEFAULTDIR/vertmp$$
TEMPFILEV2=$DEFAULTDIR/vertemp$$
LIST=$DEFAULTDIR/list$$
TITLE="AUTOTBACK 3.4"
BACKTITLE="A dialog driven backup utility (press [ESC] twice to exit)"
INTERRUPT="echo -en [ESC] Pressed, exiting... "
HEADER="Backup Report for $HOSTNAME
(c)1991-2012 xxxxxxxx Inc.
===============================================================================
`date`
"
#########################
# Define main functions #
#########################
########
# lock #
########
lock ()
{
# Check if another job is running
if [ -r $LOCK ]
then
# if we have wall, announce the trouble
if [ ! "$(whereis wall | cut -d: -f2)" = "" ]; then wall " We have a little issue with the BACKUP ! Please verify $DEFAULTDIR"; fi
echo "`date` - Another job is running or the last backup did not finished well. Please check $DEFAULTDIR !" >> $REPORTFILE
# check the age of the lockfile, if it is older then 23 hrs, chances are that nobody checked the log
((DIFF=`date +%s`-`cat $LOCK`))
if [ $DIFF -gt 82800 ]; then echo "`date` - Lockfile more than 23 hours old, autocleaning... the backup will run!" >> $REPORTFILE; rm -f $LOCK; fi
if [ -r $LOCK ]
then
if [ ! "$(whereis mail | cut -d: -f2)" = "" ]; then cat $REPORTFILE | mail -s "$0 Warning from $HOSTNAME" $REC 2>/dev/null; fi
if [ "$PRN" = "" ]; then echo "Skip print, no printer defined" >> $REPORTFILE; elif [ ! "$(whereis lp |cut -d: -f2)" = "" ]; then lp -d $PRN $REPORTFILE; fi
exit 2
fi
fi
# Cleanup obsolete traces and create defaultdir
rm -rf $DEFAULTDIR 2> /dev/null
mkdir -p $DEFAULTDIR 2> /dev/null
if [ ! -d $DEFAULTDIR ] ; then echo "CAN'T MAKE $DEFAULTDIR"; exit 3; fi
touch $REPORTFILE $TEMPFILE $TEMPFILE2 $TEMPFILEV $TEMPFILEV2 $LIST
# Create lockfile
echo "`date +%s`">$LOCK
}
##################
# extract dialog #
##################
extract_dialog ()
{
# If dialog is not in path and the system is linux - !!! TBD - NOT USED IN v3.4 !!!
if [ ! "`uname -a | grep Linux`" == "" ]; then
echo "Dialog not found, Do you want to try to extract our own dialog? y/n"
read extract
if [ "$extract" = "y" ] || [ "$extract" = "Y" ]; then
# Find the tar archive at the end of this script. It starts after the line "---DEMARK---"
# It was added there with a simple 'cat binary.tar.bz2 >> $this_script'
binstart=`expr $(grep --text --line-number '^---DEMARK---$' $0 | cut -f1 -d:) + 1`
# Extract the tar archive on /tmp
tail -n +$binstart $0 | tar -C/tmp -xjvf -
fi
fi
}
#####################
# graphic interface #
#####################
void ()
{
# Make the TERM display white on blue
setterm -clear all -foreground white -background blue
# Check if another job is running
lock
# present the user the choice of backup, resctore or scheduler
dialog --title "$TITLE" --backtitle "$BACKTITLE" --nocancel --menu "Choose an Option" 11 30 3 1 "Create a Backup" 2 "Restore from Backup" 3 "Schedule a Backup" 2>/tmp/input.$$
sel=$?
choice=`cat /tmp/input.$$`
rm -f /tmp/input.$$
case $sel in
0)
if [ "$choice" = "1" ]; then
#dialog choose what, where, to backup, to whom we send email, where we print (if we print)
dialog --title "$TITLE (SPACE to select what to save)" --backtitle "$BACKTITLE" --nocancel \
--fselect "/" 12 46 2>/tmp/input.$$
sel=$?
SRC=`cat /tmp/input.$$`
rm -f /tmp/input.$$
case $sel in
0);;
255) $INTERRUPT && rm -f $LOCK && exit 1;;
esac
dialog --title "$TITLE" --backtitle "$BACKTITLE" --nocancel \
--inputbox "Select the destination device" 8 25 /dev/st0 2>/tmp/input.$$
sel=$?
DES=`cat /tmp/input.$$`
rm -f /tmp/input.$$
case $sel in
0);;
255) $INTERRUPT && rm -f $LOCK && exit 1;;
esac
dialog --title "$TITLE" --backtitle "$BACKTITLE" --nocancel \
--inputbox "Type the notification emails" 8 47 "backupreport@xxxxxxxx.com root@localhost" 2>/tmp/input.$$
sel=$?
REC=`cat /tmp/input.$$`
rm -f /tmp/input.$$
REC=\"$REC\"
case $sel in
0);;
255) $INTERRUPT && rm -f $LOCK && exit 1;;
esac
dialog --title "$TITLE" --backtitle "$BACKTITLE" --nocancel \
--inputbox "Type the Printer name (if any)" 8 25 2>/tmp/input.$$
sel=$?
PRN=`cat /tmp/input.$$`
rm -f /tmp/input.$$
case $sel in
0);;
255) $INTERRUPT && rm -f $LOCK && exit 1;;
esac
dialog --title "$TITLE" --backtitle "$BACKTITLE" --nocancel \
--infobox "Performing the Backup procedure. Please wait..." 6 25
# call the backup function with the right command line options. Remove lock before
rm -f $LOCK && backup
fi
if [ $choice = 2 ]; then
##dialog choose where to restore, from where, to whom we send email, where we print (if we print)
dialog --title "$TITLE (SPACE to select where to save)" --backtitle "$BACKTITLE" --nocancel \
--fselect "/" 12 47 2>/tmp/input.$$
sel=$?
SRC=`cat /tmp/input.$$`
rm -f /tmp/input.$$
case $sel in
0);;
255) $INTERRUPT && rm -f $LOCK && exit 1;;
esac
dialog --title "$TITLE" --backtitle "$BACKTITLE" --nocancel \
--inputbox "Select the source device" 8 25 /dev/st0 2>/tmp/input.$$
sel=$?
DES=`cat /tmp/input.$$`
rm -f /tmp/input.$$
case $sel in
0);;
255) $INTERRUPT && rm -f $LOCK && exit 1;;
esac
dialog --title "$TITLE" --backtitle "$BACKTITLE" --nocancel \
--inputbox "Type the notification emails" 8 47 "backupreport@xxxxxxxx.com root@localhost" 2>/tmp/input.$$
sel=$?
REC=`cat /tmp/input.$$`
rm -f /tmp/input.$$
REC=\"$REC\"
case $sel in
0);;
255) $INTERRUPT && rm -f $LOCK && exit 1;;
esac
dialog --title "$TITLE" --backtitle "$BACKTITLE" --nocancel \
--inputbox "Type the Printer name (if any)" 8 25 2>/tmp/input.$$
sel=$?
PRN=`cat /tmp/input.$$`
rm -f /tmp/input.$$
case $sel in
0);;
255) $INTERRUPT && rm -f $LOCK && exit 1;;
esac
dialog --title "$TITLE" --backtitle "$BACKTITLE" --nocancel \
--infobox "Performing the Restore procedure. Please wait..." 6 25
# call the restore function with the right command line options. remove lock before
rm -f $LOCK && restore
fi
if [ $choice = 3 ]; then
# before schedule a new backup, check is there is another one already programmed
myname=`echo $0 | sed -e's/\.\///'` # Remove ./ from $0
if [ ! `crontab -l | grep -c $myname` = 0 ]; then
dialog --title "$TITLE" --backtitle "$BACKTITLE" --yes-label "Keep" --no-label "Delete" --yesno "A backup is alredy scheduled, What do you want to do with it? \n `crontab -l | grep $myname`" 10 46
sel=$?
case $sel in
0) # keep the old scheduled backups in crontab, nothing to do
;;
1)
# delete old backup from crontab
crontab -l | sed -e "/$myname/d" > /tmp/tmpcron.$$
/usr/bin/crontab < /tmp/tmpcron.$$
rm -f /tmp/tmpcron.$$
;;
255) $INTERRUPT && rm -f $LOCK && exit 1;;
esac
fi
##start to schedule. choose days of week (MON-FRI preselected)
dialog --title "$TITLE" --backtitle "$BACKTITLE" --nocancel --checklist "Choose days of Backup (Use SPACE to select)" 18 26 12 0 Sunday off 1 Monday on 2 Tuesday on 3 Wednesday on 4 Thursday on 5 Friday on 6 Saturday off --and-widget 2>/tmp/input.$$
sel=$?
sed -i -e 's/\"//g' -e 's/\ /\,/g' /tmp/input.$$
week=`cat /tmp/input.$$`
rm -f /tmp/input.$$
case $sel in
0);;
255) $INTERRUPT && rm -f $LOCK && exit 1;;
esac
##choose time of backup (23:30 seems to be a good default choice)
dialog --title "$TITLE" --backtitle "$BACKTITLE" --nocancel --timebox "Choose time for Backup (Use arrows to modify)" 5 26 23 30 00 2>/tmp/input.$$
sel=$?
hr=`cat /tmp/input.$$ | cut -f1 -d:`
min=`cat /tmp/input.$$ | cut -f2 -d:`
rm -f /tmp/input.$$
case $sel in
0);;
255) $INTERRUPT && rm -f $LOCK && exit 1;;
esac
# choose what, where, to whom we send email, where we print (if we print)
dialog --title "$TITLE (SPACE to select what to save)" --backtitle "$BACKTITLE" --nocancel \
--fselect "/" 12 46 2>/tmp/input.$$
sel=$?
SRC=`cat /tmp/input.$$`
rm -f /tmp/input.$$
case $sel in
0);;
255) $INTERRUPT && rm -f $LOCK && exit 1;;
esac
dialog --title "$TITLE" --backtitle "$BACKTITLE" --nocancel \
--inputbox "Select the destination device" 8 25 /dev/st0 2>/tmp/input.$$
sel=$?
DES=`cat /tmp/input.$$`
rm -f /tmp/input.$$
case $sel in
0);;
255) $INTERRUPT && rm -f $LOCK && exit 1;;
esac
dialog --title "$TITLE" --backtitle "$BACKTITLE" --nocancel \
--inputbox "Type the notification emails" 8 47 "backupreport@xxxxxxxx.com root@localhost" 2>/tmp/input.$$
sel=$?
REC=`cat /tmp/input.$$`
rm -f /tmp/input.$$
REC=\"$REC\"
case $sel in
0);;
255) $INTERRUPT && rm -f $LOCK && exit 1;;
esac
dialog --title "$TITLE" --backtitle "$BACKTITLE" --nocancel \
--inputbox "Type the Printer name (if any)" 8 25 2>/tmp/input.$$
sel=$?
PRN=`cat /tmp/input.$$`
rm -f /tmp/input.$$
case $sel in
0);;
255) $INTERRUPT && rm -f $LOCK && exit 1;;
esac
#insert the line in crontab
crontab -l > /tmp/tmpcrontab.$$
echo "$min $hr * * $week $myname backup $SRC $DES $REC $PRN" >> /tmp/tmpcrontab.$$
/usr/bin/crontab < /tmp/tmpcrontab.$$
rm -f /tmp/tmpcrontab.$$
dialog --title "$TITLE" --backtitle "$BACKTITLE" --nocancel \
--infobox "New crontab is installed...\n `crontab -l | grep $myname`" 10 45
fi
;;
255) $INTERRUPT && rm -f $LOCK && exit 1;;
esac
# end of graphical part, restore TERM
setterm -default
# remove lock
sleep 1
rm $LOCK
}
###################
# backup & verify #
###################
backup ()
{
# Check if another job is running
lock
# Start backup
if [ ! "$PRECOMMAND" == "" ]; then
$PRECOMMAND >>$REPORTFILE
fi
echo "$HEADER
Backup of $HOSTNAME started
The command line was: $0 backup $SRC $DES $REC $PRN
">>$REPORTFILE
# Start saving
cd $SRC
echo "Start WRITING $SRC to $DES on `date`">>$REPORTFILE
# In any case exclude /proc /sys /tmp /mnt
if [ "$ARCHIVER" == "tar" ]
then
tar --verbose --exclude=/proc --exclude=/sys --exclude=/tmp --exclude=/mnt --totals -b2048 -cpvf $DES $SRC >>$TEMPFILE 2>$TEMPFILE2
else
echo "Enumerating the list of files and removing special folders
">>$REPORTFILE
find . -depth -print | grep -v "./sys/" | grep -v "./proc/" | grep -v "./tmp/" | grep -v "./mnt/" >$LIST
cat $LIST | cpio -ocvB >$DES 2>>$TEMPFILE
fi
backstat=$?
echo "
Following are the last lines recorded during saving:" >>$REPORTFILE
tail $TEMPFILE | head -9 >>$REPORTFILE
tail -n1 $TEMPFILE >>$REPORTFILE
echo "
WRITE exit status = $backstat
">> $REPORTFILE
if [ $backstat -ne 0 ]
then
if [ $backstat -eq 1 ]
then
echo "*** Backup may be incomplete or have missing files ***">>$REPORTFILE
elif [ $backstat -eq 2 ]
then
if [ `grep "Error exit delayed from previous errors" $TEMPFILE2` ]
then
echo "*** Backup may be incomplete or have missing files ***">>$REPORTFILE
else
echo "*** Backup has encounter a fatal ERROR. Please check ***">>$REPORTFILE
fi
else
echo "*** Backup may contain an ERROR ***">>$REPORTFILE
fi
else
echo "*** Backup COMPLETED OK ***">>$REPORTFILE
fi
echo "Tape WRITING completed on `date`">>$REPORTFILE
if [ ! "$ARCHIVER" == "tar" ]
then
set `tail -1 $TEMPFILE | cut -d: -f2 | cut -d" " -f2`
BACKTOT=$1
else
BACKTOT=`grep "Total bytes" $TEMPFILE2 | cut -d: -f2 | cut -d" " -f2`
fi
echo "
Total of amount of saved bytes was $BACKTOT
">>$REPORTFILE
#Tape Verify
echo "Starting VERIFY on $DES `date`">>$REPORTFILE
if [ "$ARCHIVER" == "tar" ]
then
tar --verbose --exclude=/proc --exclude=/sys --exclude=/tmp --exclude=/mnt --totals -b2048 -tpvf $DES >>$TEMPFILEV 2>>$TEMPFILEV2
else
cpio -icvtB <$DES >>$TEMPFILEV 2>>$TEMPFILEV2
fi
verstat=$?
echo "
Following are the last lines recorded during verify:" >>$REPORTFILE
tail $TEMPFILEV | head -9 >>$REPORTFILE
tail $TEMPFILEV2 | head -9 >>$REPORTFILE
echo "
VERIFY exit status = $verstat
">>$REPORTFILE
if [ $verstat -ne 0 ]
then
echo "*** Verify may contain an ERROR ***
">>$REPORTFILE
fi
echo "Verify completed for $HOSTNAME on `date`
">>$REPORTFILE
if [ ! "$ARCHIVER" == "tar" ]
then
set `tail -1 $TEMPFILEV2 | cut -d: -f2 | cut -d" " -f2`
VERTOT=$1
else
VERTOT=`grep "Total bytes" $TEMPFILEV2 | cut -d: -f2 | cut -d" " -f2`
fi
echo "Total of amount of verified bytes was $VERTOT
">>$REPORTFILE
if [[ $backstat -ne 0 || ($verstat -ne 0 || "$BACKTOT" != "$VERTOT") ]]
then
if [ $verstat -eq 1 ]
then
echo "*** Verify may be incomplete ***">>$REPORTFILE
elif [ $verstat -eq 2 ]
then
echo "*** Verify has encounter a fatal ERROR. Please check ***">>$REPORTFILE
else
echo "*** The backup may contain an ERROR ***">>$REPORTFILE
fi
# put a warning
echo "*** WARNING!!! BACKUP TRANSFER TOTALS DID NOT MATCH ***
*** PLEASE VERIFY ***
">>$REPORTFILE
# Send the report
if [ ! "$(whereis mail | cut -d: -f2)" = "" ]; then cat $REPORTFILE | mail -s "Backup ERROR on $HOSTNAME" $REC 2>/dev/null; fi
else
# Gives the OK
echo "*** Transfer Totals Concur ***
">>$REPORTFILE
# Send the report
if [ ! "$(whereis mail | cut -d: -f2)" = "" ]; then cat $REPORTFILE | mail -s "Backup OK on $HOSTNAME" $REC 2>/dev/null; fi
fi
# Print the report
if [ "$PRN" = "" ]; then echo "Skip print, no printer defined" >> $REPORTFILE; elif [ ! "$(whereis lp |cut -d: -f2)" = "" ]; then lp -d $PRN $REPORTFILE; fi
# Eject if mt is installed
if [ ! "$(whereis mt |cut -d: -f2)" = "" ]; then mt -f $DES rewoffl; fi
# remove lock
sleep 1
rm $LOCK
if [ ! "$POSTCOMMAND" == "" ]; then
$POSTCOMMAND >>$REPORTFILE
fi
}
###########
# restore #
###########
restore ()
{
# Check if another job is running
lock
# Start restore
if [ ! "$PRECOMMAND" == "" ]; then
$PRECOMMAND >>$REPORTFILE
fi
echo "$HEADER Restore started on `date`
The command line was: $0 restore $SRC $DES $REC $PRN
Choosing the files to restore...">>$REPORTFILE
#choose the files to restore
echo "Type the name of the files you want to restore (CR = all the archive)
(ex: to restore everything from /etc/sysconfig type etc/sysconfi*):"
read RES
echo "Restoring $RES from $DES to $SRC." >> $REPORTFILE
mkdir -p $SRC 2>/dev/null
cd $SRC
if [ "$ARCHIVER" == "tar" ]
then
tar --exclude=/proc --exclude=/sys --exclude=/tmp --exclude=/mnt --totals -b2048 -xpvf $DES $RES >>$TEMPFILE 2>>$TEMPFILE2
else
cpio -icvdmB $RES < $DES >>$TEMPFILE 2>>$TEMPFILE2
fi
resstat=$?
echo "RESTORE exit status = $resstat
">>$REPORTFILE
if [ $resstat -ne 0 ]
then
echo "*** RESTORE may contain an ERROR ***
">>$REPORTFILE
fi
# Prepare the report
echo "Following are the special cases reported during restore:" >>$REPORTFILE
tail $TEMPFILE | head -9 >> $REPORTFILE
tail $TEMPFILE2 | head -9 >> $REPORTFILE
set `tail -1 $TEMPFILE2 | cut -d: -f2 | cut -d" " -f2`
RESTOT=$1
echo "Total of amount of restored bytes was $RESTOT
">>$REPORTFILE
# Send the report
if [ ! "$(whereis mail | cut -d: -f2)" = "" ]; then cat $REPORTFILE | mail -s "Restore report for $HOSTNAME" $REC 2>/dev/null; fi
# Print the report
if [ "$PRN" = "" ]; then echo "Skip print, no printer defined">> $REPORTFILE; elif [ ! "$(whereis lp |cut -d: -f2)" = "" ]; then lp -d $PRN $REPORTFILE; fi
# Eject if mt is installed
if [ ! "$(whereis mt |cut -d: -f2)" = "" ]; then mt -f $DES rewoffl; fi
# remove lock
sleep 1
rm $LOCK
if [ ! "$POSTCOMMAND" == "" ]; then
$POSTCOMMAND >>$REPORTFILE
fi
}
###################
# Starting script #
###################
case "$1" in
backup)
backup;;
restore)
restore;;
*)
# If it was called without parameters check if dialog exist and call the interface
if [ "$(whereis dialog | cut -d: -f2)" = "" ]; then
extract_dialog
echo "Usage: $0 backup (source) (destination) (email) (printer)
$0 restore (destination) (source) (email) (printer)
"
else
void
fi
;;
esac
# ensure a safe exit
exit 0
---DEMARK---
Monday, July 11, 2011
rotate kde cube using the accelerometer
ain't that fun? tilt the laptop and the cube rotates :) all thanks to the ST LIS3LV02DL Accelerometer
#!/bin/bash
# kde-cube-rotate
#
while true ; do
# vertical axis
#POS1=`cat /sys/devices/platform/lis3lv02d/position | awk -F , '{print$2}'`
#sleep .1
#POS2=`cat /sys/devices/platform/lis3lv02d/position | awk -F , '{print$2}'`
#horizontal axis
POS1=`cat /sys/devices/platform/lis3lv02d/position | awk -F , '{print$1}' | awk -F "(" '{print$2}'`
#sleep .1
POS2=`cat /sys/devices/platform/lis3lv02d/position | awk -F , '{print$1}' | awk -F "(" '{print$2}'`
DIS=$( wmctrl -d | grep "*" | awk '{sub(/x[0-9]+/, "", $1); print $1}'| tail -n1)
((POS=$POS1-$POS2))
#echo "pos1=$POS1 pos2=$POS2 pos=$POS display=$DIS"
if [ $POS -ge 20 ]; then
wmctrl -s $(( ${DIS} - 1 )) 2>/dev/null
sleep 1
elif [ $POS -le -20 ]; then
wmctrl -s $(( ${DIS} + 1 )) 2>/dev/null
sleep 1
fi
done
Saturday, May 28, 2011
/etc/udev/rules.d/80-automount.rules
KERNEL=="sd[a-z]", NAME="%k", SYMLINK+="usb%m", GROUP="users", OPTIONS="last_rule"
ACTION=="add", KERNEL=="sd[a-z][0-9]", SYMLINK+="usb%n", GROUP="users", NAME="%k"
ACTION=="add", KERNEL=="sd[a-z][0-9]", RUN+="/bin/mkdir -p /mnt/usb%n"
ACTION=="add", KERNEL=="sd[a-z][0-9]", PROGRAM=="/lib/udev/vol_id -t %N", RESULT=="vfat", RUN+="/bin/mount -t vfat -o rw,noauto,flush,quiet,nodev,nosuid,noexec,noatime,dmask=000,fmask=111 /dev/%k /mnt/usb%n", OPTIONS="last_rule"
ACTION=="add", KERNEL=="sd[a-z][0-9]", PROGRAM=="/lib/udev/vol_id -t %N", RESULT=="ntfs", RUN+="/bin/mount -t ntfs-3g -o rw,noauto,flush,quiet,nodev,nosuid,noexec,noatime,dmask=000,fmask=111 /dev/%k /mnt/usb%n", OPTIONS="last_rule"
ACTION=="add", KERNEL=="sd[a-z][0-9]", RUN+="/bin/mount -t auto -o rw,noauto,sync,dirsync,noexec,nodev,noatime /dev/%k /mnt/usb %n", OPTIONS="last_rule"
ACTION=="remove", KERNEL=="sd[a-z][0-9]", RUN+="/bin/umount -l /mnt/usb%n"
ACTION=="remove", KERNEL=="sd[a-z][0-9]", RUN+="/bin/rmdir /mnt/usb%n", OPTIONS="last_rule"
ACTION=="add", KERNEL=="sd[a-z][0-9]", SYMLINK+="usb%n", GROUP="users", NAME="%k"
ACTION=="add", KERNEL=="sd[a-z][0-9]", RUN+="/bin/mkdir -p /mnt/usb%n"
ACTION=="add", KERNEL=="sd[a-z][0-9]", PROGRAM=="/lib/udev/vol_id -t %N", RESULT=="vfat", RUN+="/bin/mount -t vfat -o rw,noauto,flush,quiet,nodev,nosuid,noexec,noatime,dmask=000,fmask=111 /dev/%k /mnt/usb%n", OPTIONS="last_rule"
ACTION=="add", KERNEL=="sd[a-z][0-9]", PROGRAM=="/lib/udev/vol_id -t %N", RESULT=="ntfs", RUN+="/bin/mount -t ntfs-3g -o rw,noauto,flush,quiet,nodev,nosuid,noexec,noatime,dmask=000,fmask=111 /dev/%k /mnt/usb%n", OPTIONS="last_rule"
ACTION=="add", KERNEL=="sd[a-z][0-9]", RUN+="/bin/mount -t auto -o rw,noauto,sync,dirsync,noexec,nodev,noatime /dev/%k /mnt/usb %n", OPTIONS="last_rule"
ACTION=="remove", KERNEL=="sd[a-z][0-9]", RUN+="/bin/umount -l /mnt/usb%n"
ACTION=="remove", KERNEL=="sd[a-z][0-9]", RUN+="/bin/rmdir /mnt/usb%n", OPTIONS="last_rule"
Sunday, April 24, 2011
VPN to Sonicwall's Virtual Office
#!/bin/bash
# 2011/04/22 sorin@XXXXXXXX.com
# A script to start the Sonicwall netExtender and create the necessary routes
# Sonicwall's netExtender binary is available from the VirtualOffice web interface.
#
# Define variables. In the config file the data format is TAB separated as follow:
# username password domainname ExternalIP port
#testusr tespassword LocalDomain 123.45.67.89 443
#
# Alternatively, you can define $user $pass $dom $ip $port here
prog="/usr/sbin/netExtender"
conf="/etc/sysconfig/gvpn.conf"
log="/dev/null"
if [ ! -f $prog ]; then
echo "No binary - fatal!"
exit 2
fi
if [ ! -f $conf ]; then
echo "No config, trying to set some defaults"
user=testusr
pass=testpassword
dom=LocalDomain
ip=123.45.67.89
port=443
fi
# Let's see how this script has been called
case "$1" in
start)
# if we have a conf file read the data from there
if [ -f $conf ]; then val=`sed '/^ *#/d;s/#.*//' $conf`; read user pass dom ip port < <( echo $val ); fi echo -e "Starting $prog..." $prog -u $user -p $pass -d $dom $ip:$port & >$log 2>&1
sleep 3
# after a few seconds we can try to add the route, but first \
# if we're in the same IP range, die gracefully, otherwise add the route
routenet=`sudo ifconfig | grep P-t-P | cut -d: -f2 | cut -d. -f1-3` >$log 2>&1
grp=`sudo ifconfig | grep -v P-t-P | grep '$routenet.255'` >$log 2>&1
if [ -z "$grp" ]; then
# mac users does not have "dev" in route's options, so let's add the route via a gateway
# routedev=`sudo ifconfig | grep ppp | cut -dL -f1` >$log 2>&1
# sudo route add -net $routenet netmask 255.255.255.0 dev $routedev >$log 2>&1
newip=`sudo ifconfig | grep P-t-P | cut -d: -f2 | cut -d" " -f1` >$log 2>&1
sudo route add -net $routenet.0 netmask 255.255.255.0 gw $newip >$log 2>&1
else
echo "We are in the same IP range, can't assign a route to the remote network!"
$0 stop
exit 1
fi
;;
stop)
echo -e "Stopping $prog..."
# first let's bring down the ppp interface
routedev=`sudo ifconfig | grep ppp | cut -dL -f1` >$log 2>&1
sudo ifconfig $routedev down >$log 2>&1
# then ask the pogram to terminate
sudo killall $prog >$log 2>&1
sleep 5
# if netExtender is still alive after 5 sec, force kill
if [ `ps xau | grep -v grep | grep $prog | awk '{print $2}' | wc -l` -ne "0" ]; then
sudo killall -9 $prog >$log 2>&1
fi
;;
status)
if [ `ps xau | grep -v grep | grep $prog | awk '{print $2}' | wc -l` -ne "0" ]; then
echo "$prog running with pid(s) `ps xau | grep -v grep | grep $prog | awk '{print $2}' | tr '
' ', '`"
echo "Showing route via ppp devices..." ; sudo route | grep ppp | grep -v 255.255.255.255
else
echo "$prog NOT running"
fi
;;
restart)
$0 stop
sleep 3
$0 start
;;
*)
printf "Usage: %s\n" "$(basename $0) {start|stop|status|restart}"
exit 1
esac
exit 0
# 2011/04/22 sorin@XXXXXXXX.com
# A script to start the Sonicwall netExtender and create the necessary routes
# Sonicwall's netExtender binary is available from the VirtualOffice web interface.
#
# Define variables. In the config file the data format is TAB separated as follow:
# username password domainname ExternalIP port
#testusr tespassword LocalDomain 123.45.67.89 443
#
# Alternatively, you can define $user $pass $dom $ip $port here
prog="/usr/sbin/netExtender"
conf="/etc/sysconfig/gvpn.conf"
log="/dev/null"
if [ ! -f $prog ]; then
echo "No binary - fatal!"
exit 2
fi
if [ ! -f $conf ]; then
echo "No config, trying to set some defaults"
user=testusr
pass=testpassword
dom=LocalDomain
ip=123.45.67.89
port=443
fi
# Let's see how this script has been called
case "$1" in
start)
# if we have a conf file read the data from there
if [ -f $conf ]; then val=`sed '/^ *#/d;s/#.*//' $conf`; read user pass dom ip port < <( echo $val ); fi echo -e "Starting $prog..." $prog -u $user -p $pass -d $dom $ip:$port & >$log 2>&1
sleep 3
# after a few seconds we can try to add the route, but first \
# if we're in the same IP range, die gracefully, otherwise add the route
routenet=`sudo ifconfig | grep P-t-P | cut -d: -f2 | cut -d. -f1-3` >$log 2>&1
grp=`sudo ifconfig | grep -v P-t-P | grep '$routenet.255'` >$log 2>&1
if [ -z "$grp" ]; then
# mac users does not have "dev" in route's options, so let's add the route via a gateway
# routedev=`sudo ifconfig | grep ppp | cut -dL -f1` >$log 2>&1
# sudo route add -net $routenet netmask 255.255.255.0 dev $routedev >$log 2>&1
newip=`sudo ifconfig | grep P-t-P | cut -d: -f2 | cut -d" " -f1` >$log 2>&1
sudo route add -net $routenet.0 netmask 255.255.255.0 gw $newip >$log 2>&1
else
echo "We are in the same IP range, can't assign a route to the remote network!"
$0 stop
exit 1
fi
;;
stop)
echo -e "Stopping $prog..."
# first let's bring down the ppp interface
routedev=`sudo ifconfig | grep ppp | cut -dL -f1` >$log 2>&1
sudo ifconfig $routedev down >$log 2>&1
# then ask the pogram to terminate
sudo killall $prog >$log 2>&1
sleep 5
# if netExtender is still alive after 5 sec, force kill
if [ `ps xau | grep -v grep | grep $prog | awk '{print $2}' | wc -l` -ne "0" ]; then
sudo killall -9 $prog >$log 2>&1
fi
;;
status)
if [ `ps xau | grep -v grep | grep $prog | awk '{print $2}' | wc -l` -ne "0" ]; then
echo "$prog running with pid(s) `ps xau | grep -v grep | grep $prog | awk '{print $2}' | tr '
' ', '`"
echo "Showing route via ppp devices..." ; sudo route | grep ppp | grep -v 255.255.255.255
else
echo "$prog NOT running"
fi
;;
restart)
$0 stop
sleep 3
$0 start
;;
*)
printf "Usage: %s\n" "$(basename $0) {start|stop|status|restart}"
exit 1
esac
exit 0
Subscribe to:
Posts (Atom)
