Vbs para buscar archivo y reemplazar texto dentro de el.

Scripts No hay Comentarios »

Bueno, por aqui os dejo un script sencillito que sirve para buscar un archivo a partir de un directorio dado.

Una vez encontrado o encontrados (si existe mas de uno con el mismo nombre también lo localiza). Una vez encontrado sustituye texto dentro de el.

Este script ha sido usado para migrar a los usuarios de un servidor con Oracle 9i a otro con Oracle 11g, por eso el fichero que se busca es el tnsnames.ora.

Visual Basic:
  1. strDir = "c:\oracle\"
  2. Const ForReading = 1
  3. Const ForWriting = 2
  4.  
  5. Set FSO = CreateObject("Scripting.FileSystemObject")
  6. Set objDir = FSO.GetFolder(strDir)
  7.  
  8. getInfo(objDir)
  9.  
  10. Sub getInfo(pCurrentDir)
  11.  
  12. For Each aItem In pCurrentDir.Files
  13. If LCase(Right(Cstr(aItem.Name), 12)) = "tnsnames.ora" Then
  14. 'wscript.echo pCurrentDir
  15. wscript.Echo pCurrentDir &"\"& aItem.Name 'todos los archivos tnsnames.ora
  16. 'Capturo todo el texto del fichero
  17. set objFile =FSO.OpenTextFile(pCurrentDir & "\" & aItem.Name, ForReading)
  18. strText=objFile.ReadAll
  19. objFile.Close
  20. 'reemplazo el texto en la variable
  21. strNewText = Replace(strText, "172.31.0.43","172.31.0.13")
  22. 'escribo de nuevo el fichero con el texto cambiado
  23. Set objFile=FSO.OpenTextFile(pCurrentDir &"\"& aItem.Name, ForWriting)
  24. objFile.WriteLine strNewText
  25. objFile.Close
  26.  
  27. End If
  28. Next
  29.  
  30. For Each aItem In pCurrentDir.SubFolders
  31. getInfo(aItem) 'recursivo
  32. Next
  33.  
  34. End Sub

Ale, si alguien busca algo parecido ya lo tiene escrito. Dejar un comentario si os apetece.

Eliminar archivos en subdirectorios recursivamente con Ubuntu

Scripts, Ubuntu No hay Comentarios »

Ya llevaba yo un tiempo queriendo estandarizar la eliminación de ficheros con un tipo de extensión a partir de un directorio padre. Hasta ahora y por las prisas lo realizaba con un script personalizado para cada directorio eliminando ficheros con extensión .enc.

Estos ficheros son el resultado de encriptar backups de bases de datos antes de enviarlas por Internet para almacenarlas fuera del edificio y así garantizar la recuperación ante un desastre que afectase al CPD.

Bueno, el caso es que despues de encriptar los ficheros de base de datos se quedaban en varios directorios y subdirectorios los ficheros backup_mysql.......tar.gz.enc y había que eliminarlos poco mas o menos que de forma personalizada ya que esos ficheros después de enviados al sitio remoto no me sirven de nada en local salvo para ocupar espacio.

Dedicando un poco de tiempo a estos comandos, sobre todo al maravilloso find es posible hacer todo esto en una sola linea de comando. Para mi que aún renqueo con los comandos de linux es todo un hallazgo.

El comando se debe ejecutar en el directorio de interés. "find" por naturaleza se mueve recursivamente, así que descenderá a todos los directorios desde el original, borrando los archivos de la extensión en cuestión.

He conseguido llegar a dos comandos que realizan la misma tarea:

  • $ find ./directorioinicial/ -name *.enc -type f -print | xargs /bin/rm -f

el segundo mas simple encontrado por ahí googleando:

  • $ find -name "*.enc" -exec rm {} \;

Aquí queda de apunte para que a alguien le resulte mas sencillo de averiguar.

Para comprobar sobre que ficheros va a actuar solo hay que cambiar el comando "rm" por "ls".

Script de apagado remoto de pcs con PowerShell

PowerShell, Scripts No hay Comentarios »

Un script muy sencillo os dejo que recoge los nombres de los equipos que queremos apagar del fichero "computers.txt" y ejecuta el comando de apagado remoto para cada uno de ellos.

Puede ser muy util para apagar los ordenadores que tus usuarios de dejan encendidos.

Se puede utilizar en el programador de tareas de windows poniendo  Powershell.exe Ruta_hasta_el_fichero_ps1 en la linea de comando a ejecutar.

Visual Basic:
  1. $reference="c:\Scripts-PowerShell\computers.txt"
  2. #[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
  3. $pingsender=new-object system.net.networkinformation.ping
  4. $file1 = [System.IO.File]::OpenText((dir $reference))
  5. $line = 1
  6. while (!$file1.EndOfStream)
  7. {
  8. $line1 = $file1.ReadLine()
  9. #[System.Windows.Forms.MessageBox]::Show($line1)
  10. $reply=$pingsender.send($line1)
  11. $estado=$reply.Status;
  12. #write-output $estado
  13. if($estado -ne "Success"){write-warning "$_ no esta disponible <$line1>";}
  14. else {
  15. (get-wmiobject -class win32_operatingsystem -computername $line1).win32shutdown(12);
  16. }
  17. $line++
  18. }
  19. $file1.Close()

Fichero de firmas para Outlook con Autoit

Active Directory, Autoit3, Scripts 3 Comentarios »

Bueno, parece ser que alguien si está interesado en crear una firma corportiva para todos los usuarios.

El procedimiento lo podemos dividir en dos fases:

  • Creacion de los ficheros que contienen las firmas mediante ejecutable de autoit que todos los usuarios ejecutan mediante el script de login al dominio. Mediante el siguiente script compilado recogemos los datos del Active Directory y los utilizamos para crear la firma en tres formatos, html, rtf y txt. Los tres formatos se crean para que según tengamos configurado nuestro outlook en uno o otro formato (html, rtf o txt) siempre exista el fichero de firmas a cargar.


#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_icon=X:\Scripts\Au3\EmailSign\EmailSign.ico
#AutoIt3Wrapper_outfile=X:\Scripts\Au3\EmailSign\EmailSign.exe
#AutoIt3Wrapper_Res_Description=Crea la firma para el perfil de outlook
#AutoIt3Wrapper_Res_Fileversion=1.1.0.0
#AutoIt3Wrapper_Res_LegalCopyright=David Suárez
#AutoIt3Wrapper_Res_Field=AutoIt Version|%AutoItVer%
#AutoIt3Wrapper_Res_Field=Fecha|%date% %time%
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****


#include <GUIConstants.au3>
#include <Misc.au3>
#include <File.au3>
#include <Process.au3>
#include <Constants.au3>
#include <string.au3>

Dim $UserObj
Dim $sigpath                = ( @AppDataDir &'\microsoft\signatures' )
Dim $sigpathOffice2007      = ( @AppDataDir &'\Microsoft\Firmas' )
Dim $msg
Dim $msg1
Dim $msg2
Dim $domain = @LogonDomain
Dim $username = @UserName
Const $ADS_NAME_INITTYPE_GC = 3
Const $ADS_NAME_TYPE_NT4 = 3
Const $ADS_NAME_TYPE_1779 = 1

$oMyError = ObjEvent("AutoIt.Error", "ComError")
$objRootDSE = ObjGet("LDAP://RootDSE")
; DNS domain name.
$objTrans = ObjCreate("NameTranslate")
$objTrans.Init ($ADS_NAME_INITTYPE_GC, "")
$objTrans.Set ($ADS_NAME_TYPE_1779, @LogonDomain)
$objTrans.Set ($ADS_NAME_TYPE_NT4, @LogonDomain & "\" & @UserName)
$strUserDN = $objTrans.Get ($ADS_NAME_TYPE_1779)
$UserObj = ObjGet("LDAP://" & $strUserDN)
DIM $fullname                = $UserObj.FullName
DIM $title                    = $UserObj.title
DIM $description            = $UserObj.description
DIM $emailaddress            = $UserObj.mail
DIM $officenumber            = $UserObj.TelephoneNumber
Dim $otherFax                = $UserObj.facsimileTelephoneNumber

Dim $Disclaimer                = ("Cuidemos del medio ambiente. Por favor no imprima este correo si no es necesario.")
Dim $Defaultsigname            = ("DefaultSign")
Dim $sigrtf                    = ("DefaultSign.rtf")
Dim $sightm                    = ("DefaultSign.htm")
Dim $sigtxt                    = ("DefaultSign.txt")

If FileExists (@ProgramFilesDir & '\Microsoft Office\Office12\outlook.exe') Then    $sigpath = $sigpathoffice2007

If Not FileExists ( $sigpath &'\'& $sigrtf) Then Call ("make_rtf")
If Not FileExists ( $sigpath &'\'& $sigtxt) Then Call ("make_txt")
If Not FileExists ( $sigpath &'\'& $sightm) Then Call ("make_html")

Func make_rtf ()
$filename1 = $sigpath & '\' & $sigrtf
$msg1 &= "{\rtf1\ansi\ansicpg1252\deff0\deflang2057{\fonttbl{\f0\fswiss\fcharset0 Arial;}}"& @CRLF
$msg1 &= "\viewkind4\uc1\pard\f0\fs20 -- \par"& @CRLF
$msg1 &= "Rmte.: " & $title & " "&$fullname & "\par"& @CRLF
$msg1 &= $description & "\par"& @CRLF
$msg1 &= "Email: " & $emailaddress & "\par"& @CRLF
$msg1 &= "Tel: 91 888 88 88 Ext. " & $officenumber & "\par"& @CRLF
If $otherFax<>'' Then $msg1 &= "Fax Servicio: " & $otherFax &"\par"& @CRLF
$msg1 &= "Fax: 91 888 88 58 \par"& @CRLF
$msg1 &= "C. Direccion, 42 \par"& @CRLF
$msg1 &= "28001 (Madrid) \par"& @CRLF
$msg1 &= "http://www.tuweb.com \par"& @CRLF
$msg1 &= $Disclaimer & "\par"& @CRLF
$msg1 &= "}"
FileWrite($filename1, $msg1 )
EndFunc

Func make_html ()
$filename = $sigpath & '\' & $sightm
If Not FileExists ( $sigpath &'\smalllogo.gif') Then FileInstall("X:\Scripts\Au3\EmailSign\smalllogo.gif", $sigpath & '\smalllogo.gif')
$msg &= "<!DOCTYPE html PUBLIC ""-//W3C//DTD XHTML 1.0 Transitional//EN"" ""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"">"& @CRLF
$msg &= "<html xmlns=""http://www.w3.org/1999/xhtml"" ><style type=""text/stylesheet"" media=""screen"">a:link, a:visited, a:hover, a:active { font-size:7.5pt;font-family:Verdana,sans-serif;color:#4E5C64; }</style>"& @CRLF
$msg &= "<BODY>"& @CRLF
$msg &= "<div style=""font-size:7.5pt; font-family:Verdana, sans-serif; color: #4E5C64"">"& @CRLF
$msg &= "<p>Rmte.: <strong>" & $title & " "& $fullname & "<br/>"& @CRLF
$msg &= $description & "</strong><br/>"& @CRLF
$msg &= "Email: <a href=""mailto:" & $emailaddress & """>" & $emailaddress & "</a><br/>"& @CRLF
$msg &= "Tel: <strong> 91 888 88 88</strong> Ext. <strong>" & $officenumber& "</strong><br />"& @CRLF
If $otherFax<>'' Then $msg &= "Fax Servicio: <strong>" & $otherFax & "</strong><br />"& @CRLF
$msg &= "Fax General: <strong> 91 888 88 58</strong><br />"& @CRLF
$msg &= "<IMG alt='' hspace=0 src='smalllogo.gif' align='baseline' border='0'><br/>"& @CRLF
$msg &= "C. Direccion, 42<br />"& @CRLF
$msg &= "28001 (Madrid)<br />"& @CRLF
$msg &= "<a href=""http://www.tuweb.com"" style=""color:#4E5C64;"">http://www.tuweb.com</a></p>"
$msg &= "<p style=""font-size:8pt;color: #669900"">" & $Disclaimer & "</p>"
FileWrite($filename, $msg )
EndFunc

Func make_txt ()
$filename2 = $sigpath & '\' & $sigtxt
$msg2 &= "-- " & @CRLF
$msg2 &= "Rmte.: " & $title & " " & $fullname & @CRLF
$msg2 &=  $description & @CRLF
$msg2 &= "Email: " & $emailaddress & @CRLF
$msg2 &= "Tel: 91 888 88 88 Ext. " & $officenumber & @CRLF
If $otherFax<>'' Then $msg2 &= "Fax Servicio: " & $otherFax & @CRLF
$msg2 &= "Fax: 91 888 88 58"& @CRLF
$msg2 &= "C. Direccion, 42"& @CRLF
$msg2 &= "28001 (Madrid)"& @CRLF
$msg2 &= "http://www.tuweb.com"& @CRLF
$msg2 &= $Disclaimer
FileWrite($filename2, $msg2 )
EndFunc

;COM Error function
Func ComError()
If IsObj($oMyError) Then
$HexNumber = Hex($oMyError.number, 8 )
SetError($HexNumber)
Else
SetError(1)
EndIf
Return 0
EndFunc ;==>ComError

  • Indicarle a las estaciones mediante el Active Directory cual es la firma que han de cargar desde el directorio de firmas de cada ordenador.
    Esta parte la tengo explicada en el post Directiva AD de firma por defecto en Outlook 2007
    por lo que no volveré a hacerlo ahora.

Descarga el script de autoit desde aqui.

WP Theme & Icons originales por N.Design Studio.
Aviso Legal Entradas RSS Comentarios RSS Acceder