Image

Image

Search This Blog

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