Image

Image

Search This Blog

Friday, January 02, 2015

Resize an LVM partition on a HP Proliant server

1. Install HP Proliant support pack 

2. If you've installed the PSP before and it is already running on your server, you can skip this step, otherwise start HP Array Configuration Utility Online for Linux. 
cd /opt/compaq/cpqacuxe/bld
./cpqacuxe -R
note: after finishing online configuration utility, you might want to stop it by running
./cpqacuxe -stop

3. Expand array and logical drive
Go to https://localhost:2381 and click on array configuration utility link.
Click on expand array - it will take some time to finish (like 8hrs). After the expansion is finished, a new button called 'expand logical drive' will appear, clicking on it will finish expanding the array.

4. Make Linux kernel recognize the new size of your hardware raid5
Reboot Linux server, run  'partprobe' or 'sfdisk -R /dev/cciss/c0d0' followed by  'fdisk -l /dev/cciss/c0d0' multiple times, 'till it shows the new size.
You might have to reboot multiple times if the new size does not appear at fdisk -l.

5. Enlarge partition with fdisk - DANGEROUS, please have a full backup first!
fdisk /dev/cciss/c0d0  (you might consider using fdisk -u /dev/cciss/c0d0 - it will display the size in sectors instead of cyclinders)
"p" - take note where the /dev/cciss/c0d0p2 (your extended partition) starts!
press "d" then "2" to remove the c0d0p2 partition - yes you wil DELETE the partition, don't reboot, don't move, dont even breathe on top of that server!!!
press "n" for new, then "p" primary partition to use the full space
Make sure the old and new partition starts at the same cylinder or sector position, otherwise, all your data will be destroyed!!!
press "t" to change partition type to LVM
"w" to write
"q" to quit
now you will need to reboot again!

6. Resize physical volume size, logical volume size and perform file system online increase:

After reboot, check again the new size:
[root@log ~]# fdisk -l /dev/cciss/c0d0
Disk /dev/cciss/c0d0: 1799.7 GB, 1799797127168 bytes
255 heads, 63 sectors/track, 218812 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes

           Device Boot      Start         End      Blocks   Id  System
/dev/cciss/c0d0p1   *           1          13      104391   83  Linux
/dev/cciss/c0d0p2              14      218813  1757509959+  8e  Linux LVM

Let's see ho many free phisical blocks we have:
[root@log ~]#vgdisplay -v | grep "Free PE"
    Finding all volume groups
    Finding volume group "VolGroup00"
  Total PE / Free PE    54337 / 17879

Now let's resize the phisical volume:
[root@log ~]# pvresize /dev/cciss/c0d0p2
  Physical volume "/dev/cciss/c0d0p2" changed
  1 physical volume(s) resized / 0 physical volume(s) not resized
 
  note: we used vgdisplay -v to check the number of free PE, let's say it's 17879.

Now let's extend the lvm: 
[root@log ~]# lvextend -l +17879 /dev/VolGroup00/LogVol02
  Extending logical volume LogVol02 to 1.60 TB
  Logical volume LogVol02 successfully resized

And finally we will resize the filesystem:
[root@log ~]# resize2fs /dev/VolGroup00/LogVol02
resize2fs 1.39 (29-May-2006)
Filesystem at /dev/VolGroup00/LogVol02 is mounted on /data; on-line resizing required
Performing an on-line resize of /dev/VolGroup00/LogVol02 to 430276608 (4k) blocks.
The filesystem on /dev/VolGroup00/LogVol02 is now 430276608 blocks long.

Ofc, steps 4 to 6 can be replaced with running offline gparted from a CD...

Monday, December 01, 2014

Stream webcam with sound

cvlc v4l2:///dev/video1 :v4l2-standard= :input-slave=alsa://hw:0,0 :live-caching=300 :sout=#"transcode{vcodec=mp4v,vb=256,scale=Auto,acodec=mp4a,ab=48,channels=1,samplerate=8000}:http{mux=asf,dst=:8080/}" :sout-keep

Tuesday, November 04, 2014

Windows Shell for TS - without Domain Controller

On the RD Session Host Configuration ,the following (compiled as c:\windows\tssession.exe) script is executed as initial shell:

;(c)2014  sorinakis@g**il.com

;msgbox, Username: %A_UserName%
AuthUsers = Administrator|administrator
Loop Parse, AuthUsers, |
{
 ifEqual, A_LoopField, %A_Username%
 {
  Sleep, 500
  Run, explorer.exe
  ;MsgBox EXPLORER Executed.
  GoTo, End
 }
else
 {
  ;MsgBox In the ELSE branch.
  Sleep, 500
  Run, D:\Partages\apps\LCM\Bin\wrun32.exe -ws -c D:\Partages\apps\LCM\etc\CBLCONFI-RZ_APP.ini utmenu
  Sleep 500
  WinMaximize, ahk_class AcucobolWClass
  IfWinExist, Cie(01)
  {
   WinMaximize,  Cie(01)
   Sleep, 500
   WinWaitClose, Cie(01)
   Sleep, 500
   Run, shutdown /l
  }
  Return
 }
}
End:
Sleep, 100
;MsgBox At the END.

Thursday, October 16, 2014

Friday, October 03, 2014

SSH BruteForce Attacks are back

I've put back the little iptables rule:

-N SSHBRUTE
-A INPUT -i eth1 -p tcp -m tcp --dport 22 -m state --state NEW -m recent -j SSHBRUTE
-A SSHBRUTE -m recent --set --name BRUTESSH --rsource 
-A SSHBRUTE -m recent --rcheck --seconds 60 --hitcount 5 --rttl --name BRUTESSH --rsource -j \ REJECT --reject-with tcp-reset
-A SSHBRUTE -m recent --rcheck --seconds 60 --hitcount 4 --rttl --name BRUTESSH --rsource -j \ LOG --log-prefix "Brute Force SSH Drop"
-A SSHBRUTE -m recent --update --seconds 60 --hitcount 4 --rttl --name BRUTESSH --rsource -j \ REJECT --reject-with tcp-reset
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

Tuesday, September 02, 2014

A simple script to import .pst in thunderbird

#!/bin/bash
#
#(c)2014 sorinakis@g*il.com

if [ "$(whereis readpste | cut -d: -f2)" = "" ]; then.
 echo "Sending you to download readpst"
 kdialog --warningcontinuecancel "Go to http://www.five-ten-sg.com/libpst/ to download, then compile and install libpst
 Once libpst is installed please re-execute this script.
 If readpst is installed, but not in path, you have to comment the first section of $0" --continue-label "Go to site"
 if [ ! $? = 0 ]; then
  echo "Cancel Pressed. Exit"
  exit 2
 fi
 xdg-open http://www.five-ten-sg.com/libpst/
 exit 0
fi

# Prepare location
wrkfld=$TMP/outlook$$
export $(dbus-launch)
mkdir $wrkfld

# Convert pst
readpst -o $wrkfld -r "`kdialog --getopenfilename ~ '*.pst' 2>/dev/null`"

# Rename folder so thunderbird understands
find $wrkfld -type d | tac | grep -v '^$wrkfld$' | xargs -d '\n' -I{} mv {} {}.sbd
find $wrkfld.sbd -name mbox -type f | xargs -d '\n' -I{} echo '"{}" "{}"' | sed -e 's/\.sbd\/mbox"$/"/' | xargs -L 1 mv

#Cleanup empty folders
find $wrkfld.sbd -empty -type d | xargs -d '\n' rmdir

kdialog --msgbox "Conversion Done! Please create a subfolder in your Thunderbird's Local Folders,.
 then manuallly move $wrkfld.sdb into ~/.thunderbird/[profile]/Mail/Local Folders/[new folder]"

Sunday, August 10, 2014

Tune UP (in fact down) Windows 2008 R2

sssc config lanmanworkstation depend= bowser/mrxsmb10/nsi
sc config mrxsmb20 start= disabled

netsh int tcp set global rss=disabled
netsh int tcp set global chimney=disabled
netsh int tcp set global autotuninglevel=disabled
netsh int ip set global taskoffload=disablednetsh int tcp set global autotuninglevel=disablednetsh int tcp set global ecncapability=disablednetsh int tcp set global timestamps=disablednetsh advf set allp state off


:: reg add "HKLM\SYSTEM\CurrentControlSet\services\Tcpip\Parameters" /v DisableTaskOffload /t REG_DWORD /d "1" /f

reg add "HKLM\SYSTEM\CurrentControlSet\services\LanmanWorkstation\Parameters" /v DisableBandwidthThrottling /t REG_DWORD /d "1" /f
reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\WinHttp" /v TcpAutotuning /t REG_DWORD /d "0" /f
reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings" /v TcpAutotuning /t REG_DWORD /d "0" /f
reg add "HKLM\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Internet Settings" /v TcpAutotuning /t REG_DWORD /d "0" /f
reg add "HKLM\SYSTEM\CurrentControlSet\services\Tcpip\Parameters" /v EnableTCPA /t REG_DWORD /d "0" /f

Friday, July 11, 2014

Watermark Printer

This is a very crude version of a "Watermark Printer" - it prints on a "preprinted paper" (e.g. something containing the company logo)


@echo off

:: ------------------------------------------------------------------

:: install redmon in %userprofile%\appdata\redmon
:: put this script in %userprofile%\appdata\redmon\email.bat
:: create new printer with port RPT1:
:: configure port redirect to %userprofile%\appdata\redmon\redrun.exe
:: port arguments
%userprofile%\appdata\redmon\email.bat  %%1

:: ------------------------------------------------------------------
:: Ghostscript configuraton
set GS_INSTALL="
%userprofile%\appdata\redmon\gs"
set GS_VERSION=8.63
:: LibTIFF configuraton
set LIBTIFF_INSTALL=
%userprofile%\appdata\redmon\GnuWin32
:: PDF viewer configuraton (no need to set, if PDF is a registered file type)
set PDF_READER=
:: Watermark background config
set BACKGROUND="
%userprofile%\appdata\redmon\\Watermark.pdf"
:: PDFTK location
set PDFTK="
%userprofile%\appdata\redmon\"
:: ------------------------------------------------------------------
:: temporary PDF directory
set PDF_DIR=%TEMP%\1
:: delete old temporary PDF directories if required
for /d %%D in ("%TEMP%\1\") do if not "%%D"=="%TEMP%\1\" rd /s /q "%%D"
:: create if required
if not exist "%PDF_DIR%" md "%PDF_DIR%"
echo myass > %PDF_DIR%\blah
:: check if file is given
if not "%~1" == "" goto CHECK_FOUND
echo ERROR: No file name given!
goto END
::----------
:CHECK_FOUND
:: check for file existence
if exist "%*" goto SET_FNE
echo ERROR: File "%*" not found!
goto END
::------
:SET_FNE
:: set input file, name and extension
call :set_input_file_name_ext "%*"
:: check file type
if "%INPUT_EXT%" == "" set INPUT_NAME=%~n1.ps
if "%INPUT_EXT%" == "" set INPUT_EXT=.ps
if "%INPUT_EXT%" == ".ps" goto PROCESS_PS
if "%INPUT_EXT%" == ".tiff" goto PROCESS_TIFF
if "%INPUT_EXT%" == ".tif" goto PROCESS_TIFF
if "%INPUT_EXT%" == ".pdf" goto PROCESS_PDF
echo ERROR: File type "%INPUT_EXT%" not supported!
goto END
:: --------
:PROCESS_PS
:: set file names
set PS_FILE=%INPUT_FILE%
set PDF_FILE=%PDF_DIR%\%INPUT_NAME%.pdf
:: convert to PDF
"%GS_INSTALL%\gs%GS_VERSION%\bin\gswin32c.exe" -dSAFER -dNumRenderingThreads#%NUMBER_OF_PROCESSORS% -sDEVICE#pdfwrite -o "%PDF_FILE%" -c .setpdfwrite -f "%PS_FILE%"
goto DISPLAY
:: ----------
:PROCESS_TIFF
:: set file names
set TIFF_FILE=%INPUT_FILE%
set PDF_FILE=%PDF_DIR%\%INPUT_NAME%.pdf
:: convert to PDF
"%LIBTIFF_INSTALL%\bin\tiff2pdf.exe" -o "%PDF_FILE%" -f "%TIFF_FILE%"
goto DISPLAY
:: ---------
:PROCESS_PDF
:: set file name
set PDF_FILE=%INPUT_FILE%
::
:: ------------------------------------------------------------------
:DISPLAY
:: open PDF file in reader
:: start /b "%PDF_READER%" "%PDF_FILE%"
::
:: apply background
%PDFTK%\pdftk.exe "%PDF_FILE%" background %BACKGROUND% output "%PDF_DIR%\output.pdf"
:: call OUTLOOK - ugly for the moment
"C:\Program Files (x86)\Microsoft Office\OFFICE14\OUTLOOK.EXE" /a "%PDF_DIR%\output.pdf"

:: ------------------------------------------------------------------
:END
exit
::
:: ------------------------------------------------------------------
:: Subroutine: set_input_file_name_ext
:: Arguments:  %1 = "path/name.ext"
:: Purpose:    set environment vars to input file, name and extension
:: ------------------------------------------------------------------
:set_input_file_name_ext
set INPUT_FILE=%~1
set INPUT_NAME=%~n1
set INPUT_EXT=%~x1
goto :eof
:: ------------------------------------------------------------------

Thursday, June 05, 2014

Allow login only if the member of a certain OU comes from a certain IP subnet

@echo off
:: (c)2014 sorinakis@g*il.com
setlocal enableextensions enabledelayedexpansion
set config=c:\pair.txt

:: find the primary OU that user belongs to
for /F "tokens=3 delims=/,CN=" %%n in ('"gpresult /R | findstr CN | findstr /I %username%"') do (
 set myou=%%n
)
:: echo myou is: !myou!

:: find the client subnet (need gettscip.exe from www.ctrl-alt-del.com.au in the path somewhere)
for /F "tokens=2 delims=/: " %%f in ('gettscip.exe') do (
 for /F "tokens=1-3 delims=/." %%g in ('echo %%f') do set mynet=%%g.%%h.%%i
)
:: echo mynet is: !mynet!

:: read the config file containing the pair IP_subnet/Organisational_Unit (or group)
:: the pair have to be separated by a space, ex: '192.168.1 Users' comments start with ;
for /F "eol=; tokens=1,2 delims=/ " %%l in ('type !config!') do (
 set net=%%l
:: set group=%%m
 set ou=%%m

:: find if the user belongs to a group
rem for /f %%f in ('"net user /domain %username% | findstr /i %group%"') do set /a ingroup=yes

:: if the two pairs are identical, the user can login from that subnet
 if "!net!"=="!mynet!" (
::  if "!ingroup!"=="yes" (
 if /I "!ou!"=="!myou!" (
   set canrun=yes
  )
 )
)
::echo canrun: !canrun!

:: if the user can't login let him know, then end the session
if NOT "!canrun!"=="yes" (
 echo Sorry %username%, "!myou!" are NOT ALLOWED to login from !mynet!.0/24
 msg %username% Sorry, %username% is NOT ALLOWED to login from this location.
 shutdown /l
)

:: Cleanup variables at end
endlocal

Tuesday, May 06, 2014

Delete old printers ond add new ones - second version

This version keeps track of the default printer :)

' s@to**.guru - Jan 08 2015 Replace the default Printer

'********************************************************************************************************************
On Error Resume Next
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objShell = CreateObject("WScript.Shell")
Set objNetwork = CreateObject("WScript.Network")
'Set wmiLocator = CreateObject("WbemScripting.SWbemLocator")
'Set wmiNameSpace = wmiLocator.ConnectServer(objNetwork.ComputerName, "root\default")
'Set objRegistry = wmiNameSpace.Get("StdRegProv")
'strComputer = "."
'Const HKEY_CLASSES_ROOT  = &H80000000
'Const HKEY_CURRENT_USER  = &H80000001
'Const HKEY_LOCAL_MACHINE = &H80000002
'Const HKEY_USERS         = &H80000003
userprrf = objShell.Environment("PROCESS")("UserProfile")
lockfile = "\prinstalled"
oldlockfile = "\printersinstalled"
strnewSrv = "\\2K12SRV\"
strOldSrv = "\\critesdc\"
arrPrinters = Array("HP Color LaserJet 4700 PCL 5c","HP Color LaserJet 4700 PCL 5c Sales","HP LaserJet 4100 Series PCL6 Sales","HP LaserJet 4250 PCL6","HP Laserjet 5100tn","Xerox WorkCentre 5655 PS","Xerox7545 PS")

'********************************************************************************************************************
' If this script was already run at least once for this user, EXIT and don't look back
If (objFSO.FileExists(userprrf & lockfile)) Then
  Wscript.Quit
End If
' Delete old lockfile
objFSO.DeleteFile(userprrf & oldlockfile)
'' If we're on the TS server create lockfile and Exit!
'If objNetwork.ComputerName = "2K12TS1" Then
'  Set objFile = objFSO.CreateTextFile(userprrf & lockfile, true)
'  Set objFile = objFSO.GetFile(userprrf & lockfile)
'  objFile.Attributes = 2
'  Wscript.Quit
'End if

'********************************************************************************************************************
' Make spooler autostart without waiting
' use Microsoft's way of getting StdRegProv, set_binary is special!
'Set oRegistry = _
'   GetObject("Winmgmts:root\default:StdRegProv")
'strPath = "SYSTEM\CurrentControlSet\Services\Spooler"
'uBinary = Array(80,51,01,00,00,00,00,00,00,00,00,00,03,00,00,00,20,00,64,00,01,00,00,00,00,00,00,00,01,00,00,00,00,00,00,00,01,00,00,00,00,00,00,00)
'Return = oRegistry.SetBinaryValue(HKEY_LOCAL_MACHINE, _
'   strPath, _
'   "FailureActions", _
'   uBinary)
'oShell.RegWrite "HKLM\SYSTEM\CurrentControlSet\Services\Spooler\Start", 2, "REG_DWORD"

'********************************************************************************************************************
' get the default printer
strdefValue = "HKCU\Software\Microsoft\Windows NT\CurrentVersion\Windows\Device"
strdefPrinter = objShell.RegRead(strdefValue)
strdefPrinter = Split(strdefPrinter, ",")(0)
'wscript.Echo "Actual default printer: " & strdefPrinter
' put the default printer into the lockfile if we want to keep it for historical records
'Set objFile = objFSO.CreateTextFile(userprrf & lockfile)
'objFile.Write strdefPrinter & vbCrLf
'objFile.Close

'********************************************************************************************************************
'Delete old printers using either printui.dll or AddWindowsPrinterConnection
wscript.sleep 100
For Each strPrn in arrPrinters
strPrinter = (strOldSrv & strPrn)
'wscript.echo "removing "  & strPrinter
strCmd = "rundll32 printui.dll,PrintUIEntry /dn /n """ & strPrinter & """ /q"
      objShell.Run strCmd,,true
'    objNetwork.RemoveWindowsPrinterConnection strOldSrv & strPrn
Next

'********************************************************************************************************************
' to make sure all printers are removed, Deletes RegistryKey with all subkeys in Network printers
'sPath = "Printers\Connections"
'lRC = DeleteRegEntry(HKEY_CURRENT_USER, sPath)
'Function DeleteRegEntry(sHive, sEnumPath)
' Attempt to delete key.  If it fails, start the subkey enumration process.
'lRC = objRegistry.DeleteKey(sHive, sEnumPath)
' The deletion failed, start deleting subkeys.
'If (lRC <> 0) Then
' Subkey Enumerator  
'On Error Resume Next  
'lRC = objRegistry.EnumKey(HKEY_CURRENT_USER, sEnumPath, sNames)  
'For Each sKeyName In sNames    
'If Err.Number <> 0 Then Exit For    
'lRC = DeleteRegEntry(sHive, sEnumPath & "\" & sKeyName)  
'Next  
'On Error Goto 0
' At this point we should have looped through all subkeys, trying to delete the key again.  
'lRC = objRegistry.DeleteKey(sHive, sEnumPath)
'End If
'End Function
' Now let's recreate only the "root" Key we deleted before
'objRegistry.CreateKey HKEY_CURRENT_USER,sPath

'********************************************************************************************************************
' we have zero network printers, let`s remove all unused drivers by using Microsoft`s own prndrvr.vbs
' first restart print spooler in order to release open files
'Set objWMIService = GetObject("winmgmts:" _
'    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
'Set colServiceList = objWMIService.ExecQuery _
'        ("Select * from Win32_Service where Name='Spooler'")
'For each objService in colServiceList
'     errReturn = objService.StopService()
'Next
'wscript.sleep 1000
'Set colServiceList = objWMIService.ExecQuery _
'    ("Select * from Win32_Service where Name='Spooler'")
'For each objService in colServiceList
'     errReturn = objService.StartService()
'Next
'oShell.Run "cscript %systemroot%\system32\prndrvr.vbs -x"

'********************************************************************************************************************
'Add new printers using either printui.dll or AddWindowsPrinterConnection
wscript.sleep 100
For Each strPrn in arrPrinters
strPrinter = (strNewSrv & strPrn)
'wscript.echo "installing "  & strPrinter
strCmd = "rundll32 printui.dll,PrintUIEntry /in /n """ & strPrinter & """ /u /q /Gw"
      objShell.Run strCmd,,true
'    objNetwork.AddWindowsPrinterConnection strNewSrv & strPrn
Next

'********************************************************************************************************************
' Try to put back the default printer
'Set objFile = objFSO.OpenTextFile(userprrf & lockfile)
'Do Until objFile.AtEndOfStream
'    strNewDefPrinter = objFile.ReadLine
'Loop
'objFile.Close

strNewDefault = (Replace(strdefPrinter,strOldSrv, strNewSrv))
'wscript.Echo "New default printer: " & strNewDefault
strCmd = "rundll32 printui.dll,PrintUIEntry /y /n """ & strrNewDefault & """ /u /q /Gw"
      objShell.Run strCmd,,true
'objNetwork.SetDefaultPrinter strNewDefault


'********************************************************************************************************************
' Tell the user to check his default printer
beep = chr(007)
objShell.Run "cmd /c @echo " & beep & beep, 0
'with createobject("wscript.shell")
'   .popup "Tous vos imprimantes réseau ont été installés. SVP vérifier et changer votre imprimante DÉFAULT si nécessaire.",30, "Printers Manager"
'end with
'objShell.Exec("control printers")

'********************************************************************************************************************
' We're done, let's leave a hidden file in userprofile, so at next login this script will exit
Set objFile = objFSO.CreateTextFile(userprrf & lockfile, true)
Set objFile = objFSO.GetFile(userprrf & lockfile)
objFile.Attributes = 2
Wscript.Quit

Thursday, May 01, 2014

Delete old printers and change the default

'Change default Printer and delete the old ones
'(c)2014 s@xxxxxxxx.com
' defaultlist example: service Client,\\2K12SRV\HP 4050 P005



PrintServer = "2K8SRV" 'Old Print server name goes here - case sensitive
listfile = "\defaultlist.txt"
lockfile = "\defaultprt"
Set objNetwork = CreateObject("WScript.Network")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objSysInfo = CreateObject("ADSystemInfo")
Set objShell =  CreateObject("WScript.Shell")
userprrf = objShell.Environment("PROCESS")("UserProfile")
strComputer = "."
'strCurPath = CreateObject("Scripting.FileSystemObject").GetAbsolutePathName(strComputer)
strCurPath = "\\2k12srv\netlogon\deploy" ' relpath doesn't seems to work on UNC
 wscript.echo strCurPath
If (objFSO.FileExists(userprrf & lockfile)) Then
 'Debug
 'with createobject("wscript.shell")
 '.popup userprrf & "Lockfile EXIST!" , 1 , "Info"
 'end with
 Wscript.Quit
End If

'On Error Resume Next
strName = objSysInfo.UserName
' Split full username by comma (warning: comma is a valid char in OU, verify personally that it doesn't exist in your OU!)
arrUserName = Split(strName, ",")
' remove OU= or DC= for the last 2 OU's
arrOU = Split(arrUserName(1), "=")
arrOU2 = Split(arrUserName(2), "=")
'put those OU toghether
strOU = arrOU2(1) & " " & arrOU(1)
' open the list of OU vs printers pairs
Set objFile = objFSO.OpenTextFile(strCurPath + listfile, 1)
 Do Until objFile.AtEndOfStream
 ' they are separated by comma, first is OU second is printer
 defaultArray = split(objFile.ReadLine,",")
 readOU=defaultArray(0)
 defaultprt=defaultArray(1)
 ' Debug
 'with createobject("wscript.shell")
 '.popup "Check: """ & strOU & """ = """ & readOU & """ Choose """ & defaultprt & """. " , 1 , "Info"
 'end with
 If strOU = readOU Then
  ' Debug
  'with createobject("wscript.shell")
  '.popup "Found: """ & strOU & """ = """ & readOU & """ Printer: """ & defaultprt & """. " , 5 , "Info"
  'end with
  ' first ensure that the printer is installed, then set it default
  objNetwork.AddWindowsPrinterConnection defaultprt
  objNetwork.SetDefaultPrinter defaultprt
  exit do
 End If
Loop
objFile.Close

'Remove old printers
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colInstalledPrinters =  objWMIService.ExecQuery _
    ("Select * from Win32_Printer")

For Each objPrinter in colInstalledPrinters
    'Debug
    'with createobject("wscript.shell")
  '.popup "Name: " & objPrinter.Name , 1 , "Info"
  'end with
  'Wscript.Echo "Name: " & objPrinter.Name
    i = 0
    ReDim Preserve arrPrinterName(i)
    arrPrinterName(i) = objPrinter.Name
        If InStr(arrPrinterName(i), PrintServer) Then
            Set objNetwork = WScript.CreateObject("WScript.Network")
            'Debug
        'with createobject("wscript.shell")
      '.popup "Removing: " & arrPrinterName(i) , 5 , "Info"
      'end with       
            objNetwork.RemovePrinterConnection arrPrinterName(i)
            i=i+1
        Else
            'Debug
        'with createobject("wscript.shell")
      '.popup "Skipped: " & arrPrinterName(i) , 5 , "Info"
      'end with       
        End If

Next

' Leave a lockfile in user's home
Set objFile1 = objFSO.CreateTextFile(userprrf & lockfile)
Wscript.Quit

Thursday, April 03, 2014

Modify ANZIOLITE.DEF

@echo off
echo (c) 2014 sorin@xxxxxxxx.com

setlocal enableextensions enabledelayedexpansion

set anzio15=Anzio15
set anzio16=Anzio16
set anzio17=Anzio17
set tgtfile=ANZIOWIN.DEF

for %%x in ( !anzio15! !anzio16! !anzio17! ) do (
 for %%A IN ( "!programfiles!" "!programfiles(x86)!" ) do (
  set mypath=%%~A\%%x\%tgtfile%
  ::echo mypath is: !mypath!
  if exist "!mypath!" (
   ::echo anziowin found in !mypath!
   %0\..\ssed.exe -e "s/allow-quit=1/allow-quit=0/g" -e "s/prompt-to-save=0/prompt-to-save=2/g" "!mypath!" > "!mypath!.new"
   move /Y "!mypath!" "!mypath!.old"
   move /Y "!mypath!.new" "!mypath!"
   attrib +R "!mypath!"
  )
 )
)

if exist %appdata%\Anzio Lite\%tgtfile% (
 ::echo anziowin found in appdata
 %0\..\ssed.exe -e "s/allow-quit=1/allow-quit=0/g" -e "s/prompt-to-save=0/prompt-to-save=2/g" "%appdata%\Anzio Lite\%tgtfile%" > "%appdata%\Anzio Lite\%tgtfile%.new" 
 move /Y "%appdata%\Anzio Lite\%tgtfile%" "%appdata%\Anzio Lite\%tgtfile%.old"
 move /Y "%appdata%\Anzio Lite\%tgtfile%.new" "%appdata%\Anzio Lite\%tgtfile%"
 attrib +R "%appdata%\Anzio Lite\%tgtfile%"
)

::End
endlocal

Sunday, March 09, 2014

Setup Outlook profile and hack the location of Documents

'Setup Outlook profile and hack the location of My Documents without GPO
'(c)2010 neXt

Set WshShell = CreateObject("WScript.Shell")
On error Resume Next

set env = WshShell.Environment("PROCESS")
Set WshNet = CreateObject("WScript.Network")
homedrv =  wshshell.regread("HKEY_CURRENT_USER\Volatile Environment\HOMEDRIVE")
homedir = wshshell.regread("HKEY_CURRENT_USER\Volatile Environment\HOMEPATH")
strUsername = WshNet.Username
if (IsEmpty(homedrv) Or IsEmpty(homedir)) then
        dim WshNet, WMIService, Account
        Set WshNet = WScript.CreateObject("WScript.Network")
        Set WMIService = GetObject("winmgmts:\\.\root\cimv2")
        Set Account = WMIService.Get("Win32_UserAccount.Name='" & WshNet.UserName & "',Domain='" & WshNet.UserDomain & "'")

        userprofile = WshShell.ExpandEnvironmentStrings(WshShell.RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\" + Account.SID
 + "\ProfileImagePath"))
else

        userprofile = homedrv & homedir
end if

set objFSO = CreateObject("Scripting.FileSystemObject")

If objFSO.FolderExists("c:\Users\" & strUsername & "\Documents") Then
'with createobject("wscript.shell")
'.popup "Moving c:\Users\" & strUsername & "\Documents To " & userprofile, 1, "Info"
'end with
objFSO.CopyFolder "c:\Users\" & strUsername & "\My Documents", userprofile & "\Documents", TRUE
objFSO.DeleteFolder "c:\Users\" & strUsername & "\Documents"
End If

If objFSO.FolderExists("c:\Utilisateurs\" & strUsername & "\Documents") Then
'with createobject("wscript.shell")
'.popup "Moving c:\Users\" & strUsername & "\Documents To " & userprofile, 1, "Info"
'end with
objFSO.CopyFolder "c:\Utilisateurs\" & strUsername & "\My Documents", userprofile & "\Documents", TRUE
objFSO.DeleteFolder "c:\Utilisateurs\" & strUsername & "\Documents"

End If

If objFSO.FolderExists("c:\Documents and Users\" & strUsername & "\My Documents") Then
'with createobject("wscript.shell")
'.popup "Moving c:\Documents and Users\" & strUsername & "\My Documents To " & userprofile, 1, "Info"
'end with
objFSO.CopyFolder "c:\Documents and Users\" & strUsername & "\My Documents", userprofile, TRUE
objFSO.DeleteFolder "c:\Documents and Users\" & strUsername & "\My Documents"
End If

If objFSO.FolderExists("c:\Documents and Users\" & strUsername & "\Mes Documents") Then
'with createobject("wscript.shell")
'.popup "Moving c:\Documents and Users\" & strUsername & "\Mes Documents To " & userprofile, 1, "Info"
'end with
objFSO.CopyFolder "c:\Documents and Users\" & strUsername & "\Mes Documents", userprofile, TRUE
objFSO.DeleteFolder "c:\Documents and Users\" & strUsername & "\Mes Documents"
End If

WSHShell.RegDelete "HKEY_CURRENT_USER\Software\Microsoft\Office\12.0\Outlook\Setup\First-Run"
WSHShell.RegWrite "HKEY_CURRENT_USER\Software\Microsoft\Office\12.0\Outlook\Setup\FirstRunDialog","False"
WSHShell.RegWrite "HKEY_CURRENT_USER\Software\Microsoft\Office\12.0\Outlook\Setup\ImportPRF","\\server\netlogon\outlook.prf"
WSHShell.RegDelete "HKEY_CURRENT_USER\Software\Microsoft\Office\14.0\Outlook\Setup\First-Run"
WSHShell.RegWrite "HKEY_CURRENT_USER\Software\Microsoft\Office\14.0\Outlook\Setup\FirstRunDialog","False"
WSHShell.RegWrite "HKEY_CURRENT_USER\Software\Microsoft\Office\14.0\Outlook\Setup\ImportPRF","\\server\netlogon\outlook.prf"
WSHShell.RegWrite "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders\My Video","\\server\home\%USERNAME%\Documents\Videos","REG_SZ"
WSHShell.RegWrite "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders\My Pictures","\\server\home\%USERNAME%\Documents\Pictures","REG_SZ"
WSHShell.RegWrite "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders\My Music","\\server\home\%USERNAME%\Documents\Music","REG_SZ"
'WSHShell.RegWrite "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders\Personal","%HOMEDRIVE%\%HOMEPATH%\Documents","REG_SZ"
WSHShell.RegWrite "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders\Personal","\\server\home\%USERNAME%\Documents","REG_SZ"
WSHShell.RegWrite "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders\{374DE290-123F-4565-9164-39C4925E467B}","\\server\home\%USERNAME%\Documents","REG_SZ"
WSHShell.RegWrite "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders\{374DE290-123F-4565-9164-39C4925E}","\\server\home\%USERNAME%\Documents","REG_SZ"
WSHShell.RegWrite "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders\My Video","\\server\home\%USERNAME%\Documents\Videos","REG_EXPAND_SZ"
WSHShell.RegWrite "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders\My Pictures","\\server\home\%USERNAME%\Documents\Pictures","REG_EXPAND_SZ"
WSHShell.RegWrite "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders\My Music","\\server\home\%USERNAME%\Documents\Music","REG_EXPAND_SZ"

'WSHShell.RegWrite "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders\Personal","\\server\home\%USERNAME%\Documents","REG_EXPAND_SZ"
WSHShell.RegWrite "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders\{374DE290-123F-4565-9164-39C4925E}","%HOMEDRIVE%\%HOMEPATH%\Documents","REG_EXPAND_SZ"
WSHShell.RegWrite "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders\{374DE290-123F-4565-9164-39C4925E}","\\server\home\%USERNAME%\Documents","REG_EXPAND_SZ"
WSHShell.RegWrite "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders\Personal","\\server\home\%USERNAME%\Documents","REG_EXPAND_SZ"

Tuesday, February 04, 2014

Recover / from a full backup

If we have a nightly dd of the / partition and we need to put that on a new disk, we have to follow this procedure:
let's mount the image in /tmp/1 and the new disk in /media/sdb1:

fdisk -l media/server/disk2/backup/backup,img - note the start block and the sector size, then multiply them to obtain the mount offset.

Disk /media/server/disk2/backup/backup.img: 7.5 GiB, 8004304896 bytes, 15633408 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0x0000d331

Device                              Boot Start   End  Blocks  Id System
/media/server/disk2/backup/backup.img 1 * 62  15633407 7816673 83 Linux

512*62=31744

mount -t ext4 -o loop,ro,noexec,noload,offset=31744 /media/server/disk2/backup/backup.img /tmp/1

mkfs.ext4 -O ^has_journal -E stride=2,stripe-width=1024 -b 4096 -l root /dev/sdb1

tune2fs -o journal_data_writeback /dev/sdb1
mount /dev/sdb1/ /media/sdb1

then we can copy the content of that image to the new disk:
cd /tmp/1 && find . -depth -print | cpio -padmV /media/sdb1

we need to sed the new UUID (blkid /dev/sdb1) into /media/sdb1/boot/grub/menu.lst and /media/sdb1/etc/fstab, then
mount --bind /dev /media/sdb1/dev
mount --bind /proc /media/sdb1/proc
mount --bind /sys /media/sdb1/sys
followed by chroot /media/sdb1 /bin/bash

in the chroot we need to check the value of the actual kernel in /lib/modules/xxxxxx.xx and run a mv /boot/initrd-xxxxxxx.xx.img /boot/old.img then
dracut /boot/initrd-xxxxxxx.xx.img xxxxxx.xx

As an alternative we can change the UUID of the new disk with tune2fs -U `old_uuid` /dev/device-name

Now we can run an /boot/grub/install-grub (or run grub, followed by find /boot/grub/stage1 then root (hd1,0) and  setup (hd1) ) and finally put the new disk in the machine and boot!

Friday, January 10, 2014

This one is touchy and not very fairplay ;)

It is looking at your MAC address and based on that, it creates some binary ids in global.conf. Change your MACs, remove the confs and you should be able to help your friends without the pesky time limit :)


#!/bin/bash

hw1=`echo -n 00; dd bs=1 count=5 if=/dev/random 2>/dev/null |hexdump -v -e '/1 ":%02X"'`
sudo /sbin/ifconfig eth0 | grep HW
sudo /sbin/ifconfig eth0 hw ether $hw1
sudo /sbin/ifconfig eth0 | grep HW
hw2=`echo -n 00; dd bs=1 count=5 if=/dev/random 2>/dev/null |hexdump -v -e '/1 ":%02X"'`
sudo /sbin/ifconfig wlan0 down
sudo /sbin/ifconfig wlan0 hw ether $hw2

sudo rm -rf ~/.teamxxxxxx*
sudo rm -rf ~/.config/teamxxxxxx*
sudo rm -rf /root/.teamxxxxxx*
sudo rm -rf /root/.config/teamxxxxxx*
sudo rm -rf /opt/teamxxxxxx9/config/*
sudo killall -9 teamxxxxxxd
if [ ! "$(pidof teamxxxxxxd)" ]; then
 sudo /opt/tteamxxxxxx9/tv_bin/teamxxxxxxd -d
 x=5
 while [ $x -ge 0 ]; do
  echo -en "Wait $x seconds..."\\r
  x=$(( $x - 1 ))
  sleep 1
 done
fi
sudo /opt/teamxxxxxx9/tv_bin/script/teamxxxxxx && sudo killall -9 teamxxxxxxd


For the not-officially-supported .tar.gz, just go and modify the launcher itself in the extracted folder:

#!/bin/bash

# If you can read this text, you probably attempted to start TeamXxxxxx.
# Please open a terminal (Konsole, gnome-terminal, xterm)
# Navigate to this folder (type 'cd /path/to/teamxxxxxx' [Enter])
# then execute TeamXxxxxx (type './teamxxxxxx' [Enter])

hw0=`echo -n 00; dd bs=1 count=5 if=/dev/random 2>/dev/null |hexdump -v -e '/1 ":%02X"'`
while read interface; do
sudo ip link set dev $interface address $hw0
done < <(sudo ifconfig | cut -d" " -f1 | sed '/^$/d' | grep -v lo)
sudo /usr/bin/systemctl restart NetworkManager.service

x=4
while [ $x -ge 0 ]; do
 echo -en "Wait $x seconds for the network to be up..."\\r
 x=$(( $x - 1 ))
 sleep 1
done

TV_SCRIPT_DIR="$(dirname "$(readlink -e "$0")")"
rm -rf $TV_SCRIPT_DIR/../../profile
rm -rf $TV_SCRIPT_DIR/../../config/*

source "$TV_SCRIPT_DIR/tvw_main"

Main "$@"

Wednesday, January 01, 2014

Recursively change owner/permisions

$1 is the source of the rights/ownership, $2 is the target
 
#!/bin/sh 
chmod --reference $1 $2
chown --reference $1 $2
if [ -d $1 ] 
  then 
 if [ "x`ls $1`" != "x" ] 
   then 
    for f in `ls $1` 
    do 
    $0 $1/$f $2/$f 
 done 
 fi 
fi

Sunday, December 22, 2013

Logon Script

@echo off
color 0B
TITLE Initialization de connexion avec le serveur...
echo (c)2012 Xxxxxxxx Inc. Test de la connexion...  ^


REM ********** define per location variables *********
set server=myserver
set serverip=123.45.67.89
set group=mygroup
set domain=MYDOMAIN
set mypassword=pass_1234
set maping1=net use X: \\%server%\home\%username% /yes
set maping2=net use W: "\\%server%\Dossier Partages" /yes
set maping3=net time \\%server% /set /yes
set groupmaping=net use Z: \\%server%\specialshare /yes
set vpn=rasdial "VPN connection" %username% %mypassword%
REM ********** end of specific variables *************

REM *** define generic variables ***
set tmpvar=0
set hostspath=%windir%\System32\drivers\etc\hosts
set lmhostspath=%windir%\System32\drivers\etc\lmhosts

REM *** check if the servername is added to hosts file ***
type %hostspath% | find "%server%" 1>nul 2>nul
if errorlevel 1 goto NOTFOUND

REM *** check if the server is accessible. launch vpn first if you have to ***
:FOUND
%vpn%
ping -n 5 %server% | find "TTL" 1>nul 2>nul
IF %ERRORLEVEL% == 0 goto GOOD
IF NOT %ERRORLEVEL% == 0 goto BAD

REM *** if the server is accessible map the drives and launch a second script from server ***
:GOOD
%maping1% 1>nul 2>nul
%maping2% 1>nul 2>nul
%maping3% 1>nul 2>nul
@SET LANG=ENU
@SET FILE_SERVER=%server%
\\%server%\netlogon\oxlogon.bat

REM *** Special settings for members of certain Security Groups ***
for /f %%f in ('"net user /domain %username% | findstr /i %group%"') do set /a tmpvar=1
if %tmpvar% lss 1 goto END
%groupmaping%  1>nul 2>nul
goto END

REM *** if the server is not accessible let the user know ***
:BAD
ECHO Pas de connexion avec HQ. Verifiez le access Internet!
goto END

REM *** if the servername is not into hostfile add it ***
:NOTFOUND
echo. >> %hostspath%
echo %serverip% %server% >> %hostspath%
echo. >> %hostspath%
echo. >> %lmhostspath%
echo %serverip% %server% #PRE #DOM:%domain% >> %lmhostspath%
echo. >> %lmhostspath%
echo Ajout de %server% dans %hostspath%
goto FOUND

REM *** end of script. let the user see the messages for a few seconds, then exit ***
:END
echo C`est fait, Merci!
ping -n 4 -w 1000 1.1.1.1 >nul
exit

Thursday, December 05, 2013

Network Teaming

add the file bonding.conf to /etc/modprobe.d/
add the files ifcfg-* to /etc/sysconfig/network-scripts/ and modify them
accordingly (HWADDR, IP, GW etc)


bonding.conf
 alias bond0 bonding

ifcfg.bond0
DEVICE=bond0
IPADDR=192.168.1.178
NETMASK=255.255.255.0
ONBOOT=yes
BOOTPROTO=none
USERCTL=no
BONDING_OPTS="miimon=80 mode=2"
GATEWAY="192.168.1.1"
DNS1="192.168.1.4"
DNS2="192.168.1.253"
DOMAIN="mydomain.local"


ifcfg.eth0
DEVICE=eth0
BOOTPROTO=none
ONBOOT=yes
MASTER=bond0
SLAVE=yes
USERCTL=no
HWADDR="9C:8E:99:00:00:00" #Use the REAL MAC of the card


ifcfg.eth1
DEVICE=eth1
BOOTPROTO=none
ONBOOT=yes
MASTER=bond0
SLAVE=yes
USERCTL=no
HWADDR="9C:8E:99:
00:00:01" #Use the REAL MAC of the card

ifcfg.eth2 
DEVICE=eth2
BOOTPROTO=none
ONBOOT=yes
MASTER=bond0
SLAVE=yes
USERCTL=no
HWADDR="9C:8E:99:
00:00:02" #Use the REAL MAC of the card

Sunday, November 10, 2013

My dual backup (rsync & cpio) (local & remote)

#!/bin/bash

# Define variables
interval=2
source=/mnt/raid3
diskid=backup
log=/var/log/backup-weekly.log
errlcl=254
excludefile=/tmp/exclude.$$

echo "/backup/wstn/backintime" >> $excludefile
echo "/VMWare_defaults" >> $excludefile
echo "/AllKind" >> $excludefile
echo "/Audio" >> $excludefile
echo "/Video/music" >> $excludefile
echo "/Video/Octonauts" >> $excludefile

echo `date +%Y/%m/%d\ %H:%M:%S`" Starting Backup" >> $log
# Find where the backup drive labeled "$diskid" is mounted
#location=`mount | grep \`while read input ; do blkid /dev/$input | grep $diskid | cut -d: -f1 ; done <  <(cat /proc/partitions | tail -n +2 | cut -c 26-)\` | cut -d" " -f3`
location=`mount | grep \`blkid | grep $diskid | cut -d: -f1\` | cut -d" " -f3` >/dev/null 2>>$log

# Run the backup only if the backup drive is mounted
if [ -n "$location" ]; then
    # Move all the backups one level up (recycling the oldest follewed by cp is indeed faster)
    echo `date +%Y/%m/%d\ %H:%M:%S`" Cycling local backups on $location" >> $log
    if [ -n  $location/backup$interval ]; then
    echo `date +%Y/%m/%d\ %H:%M:%S`" Temporary moving $location/backup$interval to $location/backup_tmp" >> $log
     mv -fu $location/backup$interval/ $location/backup_tmp >>$log 2>&1
    else
    echo `date +%Y/%m/%d\ %H:%M:%S`" Older backup not found. Creating an empty $location/backup_tmp" >> $log
     mkdir  $location/backup_tmp >>$log 2>&1
    fi
    while [ $interval -ge 1 ]; do
    echo `date +%Y/%m/%d\ %H:%M:%S`" Moving $location/backup$[ interval - 1 ] to $location/backup$interval" >> $log
     mv -fu $location/backup$[ interval - 1 ]/ $location/backup$interval >>$log 2>&1
     interval=$[ interval - 1 ]
    done
    # Create current backup by recycling the oldest and linking the last backup to it
    echo `date +%Y/%m/%d\ %H:%M:%S`" Moving the oldest backup from $location/backup_tmp to $location/backup$interval" >> $log
    mv -fu $location/backup_tmp/ $location/backup$interval >>$log 2>&1
    echo `date +%Y/%m/%d\ %H:%M:%S`" Using cpio to bring the differences from $location/backup$[ interval + 1 ] to $location/backup$interval" >> $log
    cp -falux $location/backup$[ interval + 1 ]/. $location/backup$interval/ >>$log 2>&1
    # cleanup old server and router backups
    echo `date +%Y/%m/%d\ %H:%M:%S`" Cleaning old backups." >>$log
    dest=$location/backup$interval/backup/server/
    find $dest -name "bkp_*.img.gz" -type f -mtime +6 -exec rm -v {} \; >>$log 2>&1
    # Take the new backup
    echo `date +%Y/%m/%d\ %H:%M:%S`" Creating the local backup." >>$log
    rsync --quiet --log-file=$log --stats --human-readable --partial --archive --recursive --times --compress --itemize-changes --one-file-system --hard-links --inplace --numeric-ids --del --links --exclude-from=$excludefile $source/ $location/backup$interval  >>$log 2>&1 ; errlcl=$?
    echo `date +%Y/%m/%d\ %H:%M:%S`" Local Backup finished." >>$log
    echo `date` > $location/backup$interval/backup_taken
else
errlcl=255
echo `date +%Y/%m/%d\ %H:%M:%S`" ERROR: Backup disk NOT FOUND!!!" >>$log 2>&1
fi


# Second backup to the offsite drive

rmtdest=/tmp/tmpmnt.$$ 
rmtsrv=root@rmtserv:/tmp/mnt/sda1
rmtftp=rmtserv:12221/USB/
rmtcifs=\\\\rmtserv\\USB
errlvl=254
echo -e '\n'`date +%Y/%m/%d\ %H:%M:%S`" Remote Backup starting." >>$log

# Check if rsync is available on the destination
needmount=`rsync -av $excludefile $rmtsrv 2>&1 | grep 'rsync: not found'`
if [ -n "$needmount" ]; then
    # Rsync is not available, mount the remote destination locally via sshfs (using ssh keys) - fallback to smb (as guest) or curlftp (need a valid ~/.netrc) 
    echo `date +%Y/%m/%d\ %H:%M:%S`" rsync not available, mounting sshfs $rmtsrv" >>$log
    mkdir -p $rmtdest >>$log 2>&1
    sshfs $rmtsrv $rmtdest >>$log 2>&1
    if [ -z "$(mount | grep $rmtdest)" ]; then
     echo `date +%Y/%m/%d\ %H:%M:%S`" sshfs not available, mounting cifs $rmtcifs" >>$log
     mount.cifs -o guest $rmtcifs $rmtdest >>$log 2>&1
    fi
    if [ -z "$(mount | grep $rmtdest)" ]; then
     echo `date +%Y/%m/%d\ %H:%M:%S`" cifs not available, mounting ftpfs $rmtftp" >>$log
     curlftpfs -o allow_other -o gid=0 -o uid=0 -o umask=000 $rmtftp $rmtdest >>$log 2>&1
    fi
     # Without rsync we'll use cpio. First we need to make sure the rmtdest has been mounted
    if [ -n "$(mount | grep $rmtdest)" ]; then
     # cleanup old server and router backups
     echo `date +%Y/%m/%d\ %H:%M:%S`" $rmtdest mounted. Cleaning remote folder." >>$log
     dest=$rmtdest/backup/server/
     find $dest -name "bkp_*.img.gz" -type f -mtime +6 -exec rm -v {} \; >>$log 2>&1
     # start syncing the backup
     echo `date +%Y/%m/%d\ %H:%M:%S`" Starting cpio data transfer." >>$log
     cd $source
     find . -depth -print |grep -v -f $excludefile | cpio --pass-through --reset-access-time --make-directories --preserve-modification-time $rmtdest  1>>$log 2> >(grep -vi "newer") >>$log ; errlvl=$?
     echo `date +%Y/%m/%d\ %H:%M:%S`" Cpio transfer finished." >>$log
     echo `date +%Y/%m/%d\ %H:%M:%S` > $rmtdest/backup_taken
    else
     errlvl=255
     echo `date +%Y/%m/%d\ %H:%M:%S`" ERROR: No rsync available and remote destination NOT MOUNTED!!!" >>$log
    fi
else
    # If rsync is available we don't need to mount anything. Cleanup old server and router backups over ssh
    echo `date +%Y/%m/%d\ %H:%M:%S`" Using rsync. Cleaning remote folder" >>$log
    ssh `echo $rmtsrv | cut -d: -f1` `find /tmp/mnt/sda1/backup/server/ -name "bkp_*.img.gz" -type f -mtime +6 -exec rm -v {} \;` >>$log 2>&1
    # perform rsync
    echo `date +%Y/%m/%d\ %H:%M:%S`" Starting remote rsync." >>$log
    rsync --quiet --log-file=$log --stats --human-readable --partial --archive --recursive --times --compress --itemize-changes --one-file-system --hard-links --inplace --numeric-ids --del --links --max-size=4G --exclude-from=$excludefile $source/ $rmtsrv >>$log 2>&1 ; errlvl=$?
    ssh `echo $rmtsrv | cut -d: -f1` $(echo `date` > /tmp/mnt/sda1/backup_taken)
    echo `date +%Y/%m/%d\ %H:%M:%S`" Remote rsync finished." >>$log
fi

# Cleanup traces
umount -fl $rmtdest >>$log 2>&1
sleep 5
if [ -z "$(mount | grep $rmtdest)" ]; then
 rmdir $rmtdest >>$log 2>&1
fi
rm -f $excludefile >>$log 2>&1
echo -e `date +%Y/%m/%d\ %H:%M:%S`" Backup finished."'\n\n' >>$log

# Send backup report
if [ "$errlcl" -eq "0" ] && [ "$errlvl" -eq "0" ]; then
 msg="Weekly Backup successfully completed."
else
 msg="Weekly Backup might contain errors."
fi
echo "Please see attached Backup Report. The exit codes were: local=$errlcl remote=$errlvl" | mail -r backup@mydomain.tld -s "$msg" -S smtp=smtp://relay.smtpserver.tld -a $log recipient@mydomain.tld

Sunday, November 03, 2013

AfterMarket Updater

That's what happen when the devs are not thinking how to update their product :D
No other comments! 
(Thou I should mention the trick that I've done in order to put the quotes in the right place )

@echo off
rem Update Logixxxx 2.0 
rem 2013/06/06 sorin@xxxxxxxx.com - rebuild the whole thing
rem 2014/03/04 sorin@xxxxxxxx.com - cleanup version detection
rem this script must be executed with administrative rights
cls

setlocal enableextensions enabledelayedexpansion

set source=\\192.168.35.214\Partage\LOGIxxxx_2_0_Mises_a_Jour
set exclude=%source%\deploy\exclude.txt
set destination32='%programfiles%\Groupe xxxxdure\Logixxxx 2.0'
set ver32="%destination32:'=%\version.txt"
set destination32="%destination32:'=%\"
set destination86='%programfiles(x86)%\Groupe xxxxdure\Logixxxx 2.0'
set ver86="%destination86:'=%\version.txt"
set destination86="%destination86:'=%\"
set /P version=<%source%\version.txt
if not defined version set version=0
set log=Logixxxx - 

if exist %destination32% (
 set log=!log! Found in Program Files.
  for /f "delims=" %%a in ('type %ver32%') do set actualversion=%%a
  if NOT "!actualversion!"=="%version%" (
  set log=!log! Update from version !actualversion! to %version%.
  xcopy %source% %destination32% /Y /S /E /H /R /I /C /EXCLUDE:%exclude%
  if exist "%allusersprofile%\Desktop" xcopy "%source%\deploy\MAJ - LOGIxxxx.lnk" "%allusersprofile%\Desktop\" /Y
  if exist "%allusersprofile%\Bureau" xcopy "%source%\deploy\MAJ - LOGIxxxx.lnk" "%allusersprofile%\Bureau\" /Y
  if exist "%public%\Desktop" xcopy "%source%\deploy\MAJ - LOGIxxxx.lnk" "%public%\Desktop\" /Y
  ) else (
  set log=!log! Same Version. No need to update.
  goto END
 )
 goto LOG
) else ( 
  set log=!log! Not found in %destination32%.
if exist %destination86% (
 set log=!log! Found in Program Files x86.
 for /f "delims=" %%i in ('type %ver86%') do set actualvers=%%i
 if NOT "!actualvers!"=="%version%" (
  set log=!log! Update from version !actualvers! to %version%.
  xcopy %source% %destination86% /Y /S /E /H /R /I /C /EXCLUDE:%exclude%
  if exist "%allusersprofile%\Desktop" xcopy "%source%\deploy\MAJ - LOGIxxxx.lnk" "%allusersprofile%\Desktop\" /Y
  if exist "%allusersprofile%\Bureau" xcopy "%source%\deploy\MAJ - LOGIxxxx.lnk" "%allusersprofile%\Bureau\" /Y
  if exist "%public%\Desktop" xcopy "%source%\deploy\MAJ - LOGIxxxx.lnk" "%public%\Desktop\" /Y
  ) else (
  set log=!log! Same Version. No need to update.
  goto END
 )
 goto LOG
) else ( 
set log=!log! Not found in %destination86%.
) )
set log=!log! Nothing to update.

:LOG
echo
echo %date% %time% - %computername%. !log! >> %source%\deploy\UpdateLogs.txt

:END
echo !log!
ping -n 2 1.1.1.1 >nul
endlocal

Saturday, October 19, 2013

Wednesday, October 02, 2013

Backup all custom MSSQL databases

@ECHO OFF
SETLOCAL

:: Set variables
set backuplocation="\\fileserver\files\Backup"
set mainsqlbase=SQLSERVER\MSSMLBIZ
set DBList=%temp%\SQLDBList.txt

:: Delete backups older than 7 days
forfiles -p %backuplocation% -s -m *.bak -d -7 -c "cmd /c del @PATH"

:: Get date in format YYYY-MM-DD (assuming the locale is US)
FOR /F "tokens=1,2,3,4 delims=/ " %%A IN ("%DATE%") DO SET NowDate=%%D-%%B-%%C

:: Build a list of databases to backup
SqlCmd -E -S %mainsqlbase% -h-1 -W -Q "SET NoCount ON; SELECT Name FROM master.dbo.sysDatabases WHERE [Name] NOT IN ('master','model','msdb','tempdb')" > "%DBList%"

:: Backup each database, prepending the date to the filename
FOR /F "tokens=*" %%I IN (%DBList%) DO (
ECHO Backing up database: %%I
SqlCmd -E -S %mainsqlbase% -Q "BACKUP DATABASE [%%I] TO DISK = N'%backuplocation%\%NowDate%_%%I.bak' WITH NOFORMAT, NOINIT,  NAME = N'MSSmallBusiness-Full Database Backup', SKIP, NOREWIND, NOUNLOAD,  STATS = 10"
ECHO.
)

:: Clean up the temp file
IF EXIST "%DBList%" DEL /F /Q "%DBList%"

ENDLOCAL

Yes, it can be done directly from the SQL itself, but it's funnier to write a script  :)

Blog Archive