elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Como proteger una cartera - billetera de Bitcoin


  Mostrar Temas
Páginas: [1]
1  Programación / Scripting / Resolucion de IP DNS VBSCRIPT en: 4 Abril 2013, 16:48 pm
Buenas tardes,

Tengo un problema, bueno uno de muchos. Ahora el problema va por VBSCRIPT planteo el requerimiento.

Tengo que realizar informacion de un una relacion de maquinas las cuales tengo que hacr ping y tengo que resolver el IP y que resuelve el DNS.

Hostname        IP       PING            DNS
MyPc          127.0.0.1  OK          MyPC.Dominio.com
Mypc2        127.0.0.2   NO_OK   No register host

Esta  informacion pasarlo a un CSV.

Pero tambien necesito trabajar con los equipos por separado es decir que me saque un log por separado de los equipos que hacen ping y los que no. esto esta en un TXT.

si alguien me puede ayudar se lo agradecería adjunto el codigo.

Código:

Dim strComputerName, ScriptPath, OnlineFileName, OfflineFileName
Dim ArgObj, OnlineFile, OfflineFile, oInputFile, InputFileName
Dim ReadLineArray(3000), a, b, c, Temp

Const ForAppending = 8
Const ForReading = 1
Const ForWriting = 2
Const ReadTheFile = False
Const CreateTheFile = True

' Valores de Formato
Const ASCII = 0
Const UniCode = -1
Const Default = -2

Set oFSO = CreateObject("Scripting.FileSystemObject")
Set objShell = WScript.CreateObject("WScript.Shell")

' ********************   Declaracion de Varibles  ********************

' Declaracion de nombre de archivos
'*********************************************************************
FilePath=CreateObject("Scripting.FileSystemObject").GetAbsolutePathName(".")


Set ArgObj = WScript.Arguments
If WScript.Arguments.count > 0 Then
  InputFileName = UCase(ArgObj(0))
Else
  InputFileName = FilePath & "\IP_List.txt"
End If

OnlineFileName = FilePath & "\OnlineSystems.txt"
OfflineFileName = FilePath & "\OfflineSystems.txt"


' Elimina los arhivos TXT Online y Offline si es que existe
'*********************************************************************
If oFSO.FileExists(OfflineFileName) = True Then
  oFSO.deletefile OfflineFileName, force
End If
If oFSO.FileExists (OnlineFileName)  Then
  oFSO.deletefile OnlineFileName, force
End If

' Crea los Archivos Online y Offline
'*********************************************************************
oFSO.CreateTextFile OnlineFileName, CreateTheFile
oFSO.CreateTextFile OfflineFileName, CreateTheFile

' Abre el archivo y lee el contenido
'*********************************************************************
Set OnlineFile=oFSO.OpenTextFile(OnlineFileName, ForWriting, ReadTheFile)
Set OfflineFile=oFSO.OpenTextFile(OfflineFileName, ForWriting, ReadTheFile)
Set oInputFile=oFSO.OpenTextFile(InputFileName, ForReading, ReadTheFile)

' Loop through the InputFile to get all the computer names and then check to see if they are online or not.

' Importa la informacion del archivo en el array
'*********************************************************************
Do while not oInputFile.AtEndOfStream
  a = a + 1
  ReadLineArray(a) = Trim(oInputFile.ReadLine) ' Reads the line of text
Loop

' Busca duplicaciones
'*********************************************************************
For b = 1 To a
  ' If data matches, then set the duplicates in the array to "" (blank)
  For c = (b + 1) To a
    If trim(ReadlineArray(b)) <> "" And trim(ReadLineArray(b)) = trim(ReadLineArray(c)) Then
      ' Found a duplicate!  Set it to blank
      ReadLineArray(c) = ""
    End If
  Next
Next

' Copy information into "output.txt" text file (exclude blank lines).
'*********************************************************************
For b = 1 To a
  If trim(ReadlineArray(b)) <> "" Then
    strComputerName = trim(ReadlineArray(b))
    IsConnectible
  End If
Next

' Cierra todos los archivos abiertos
'*********************************************************************
OnlineFile.close
OfflineFile.close

' Let user know the program has completed its operation.
wscript.echo "Finished"
'*********************************************************************

Function IsConnectible

  Dim objPing,objStatus
   
  ' Test to see if the remote machine is online or offline
'*********************************************************************
  Set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}")._
  ExecQuery("select Replysize from Win32_PingStatus where address = '" & strComputerName & "'")
   
  ' Test for the status.  If the system is Null or if its offline or does not exist on the network,
  ' then dump the results to "Offline.txt", else, dump it to "online.txt"
'*********************************************************************
  For Each objStatus in objPing
    If  IsNull(objStatus.ReplySize) Then
      ' Machine is offline --> dump the results to "Offline.txt"
      OfflineFile.Writeline strComputerName
    Else
      ' Machine is online  --> dump the results to "Online.txt"
      OnlineFile.Writeline strComputerName
    End If
  Next
   
  ' Destruye las variable de memoria
'*********************************************************************
  Set objPing=Nothing
  Set objStatus=Nothing

End Function


2  Programación / Scripting / Resolucion de IP y DNS - Powershell en: 31 Marzo 2013, 03:15 am
Hola, alguien me pueda ayudar. el problema es el siguiente que una no puedo resolverlo estoy un poco estancado.
Tengo que realizar un script que me resuleva el PING y DNS y toso esto escrtibirlo en un CSV. tengo hasta al momento el codigo pero aun no puedo armarlo dando tantas vueltas ya me quede un poco bloqueado. a ver si alguien mepuede ayudar gracias por todo.


Saludos

Código:
Clear
$log = "C:\log.log"
$output = @()
## Validar si el equipo hace PING
$PingMachines = Get-Content "C:\sql.txt"

ForEach($MachineName In $PingMachines){

    $PingStatus = Get-WmiObject Win32_PingStatus -Filter "Address = '$MachineName'" | Select-Object StatusCode
    #$tmp = New-Object Psobject -Property @{Name = $MachineName; Status = $PingStatus.StatusCode}
If ($PingStatus.StatusCode -eq 0){
$output += = "$machines - OK"
    }
Else{
    $output += = "$machines - NO_OK"
        }

## Validar si el equipo resuelve el DNS

$result = $null
    $currentEAP = $ErrorActionPreference
    $ErrorActionPreference = "silentlycontinue"
    $result = [System.Net.Dns]::GetHostbyName($MachineName)
    $ErrorActionPreference = $currentEAP
     
If($Result){
    $output += [string]$Result.HostName
}
Else{
    $output += = "$machines - No HostNameFound"
    }
 }
$output | Export-csv c:\export.csv -NoTypeInformation

3  Programación / Scripting / [VBS] Problema al ejecutar un .EXE y crear su acceso directo en: 5 Mayo 2012, 15:56 pm
Hola a todos,

tengo un problema que aun no me puedo aclarar debe ser algo simple pero no da mi cabeza para mas, estoy bloqueado. El problema que tengo es el siguiente.
tengo un Script que realiza lo siguiente.

instala un programa el ejecutable es un .exe
una vez termine de ejecutar como no te hace una acceso directo, lo genero yo. pero el problema es que realiza la primera instruccion y a la misma vez la instruccion del acceso directo. pero como aun no termina la ejecucion del .exe no puede generar el acceso directo. solo me hace la primera parte.
este es el script. alguien me puede dar alguna orientacion

Código
  1.  
  2. ********************************************************************
  3. Option Explicit ' Declaracion de las variables
  4.  
  5. Dim Wshshell, Command
  6. Dim objShell, objDesktop, objLink 'Variables
  7. Dim strAppPath, strWorkDir, strIconPath 'Variables
  8.  
  9. ' ----------------------------------------------------------'
  10. ' Ejecuta el .EXE
  11.  
  12. Set Wshshell = Wscript.createObject("WScript.Shell")
  13. Command = "mozilla.exe" ' Mozilla.exe es un ejemplo como puede ser cualquier .EXE
  14. WshShell.Run Command ' Ejecuta el comando
  15.  
  16.  
  17. ' Creación de Acceso Directo Aplicación
  18.  
  19. ' --------------------------------------------------
  20.  
  21.  
  22. strWorkDir ="z:\mozilla.exe" ' Directorio donde esta la aplicacion
  23. strAppPath = "d:\mozilla.exe" 'Ruta de la aplicación
  24.  
  25. Set objShell = CreateObject("WScript.Shell")
  26. objDesktop = objShell.SpecialFolders("D:\Users\Public\Desktop") ' Acceso directo en el escritorio
  27. Set objLink = objShell.CreateShortcut(objDesktop & "\COP - Comptabilitat Organisme Pagador.lnk") ' Nombre del acceso directo
  28.  
  29. ' ---------------------------------------------------
  30. 'Propiedades acceso ridercto
  31.  
  32. objLink.Description = "mozilla"   ' Comentario
  33. 'objLink.HotKey = "CTRL+SHIFT+X" ' Teclado de método abreviado
  34. objLink.TargetPath = strAppPath 'Ruta de la aplicación  (Destino)
  35. objLink.WindowStyle = 3
  36. objLink.WorkingDirectory = strWorkDir ' Directorio donde esta la aplicacion (Iniciar en)
  37. objLink.Save ' Guardar
  38.  
  39. WScript.Quit ' Salir
  40.  
  41.  
  42. ********************************************************************
  43.  
Saludos y espero alguna orientacion
4  Programación / Scripting / Mapeo de impresoras en red por usuarioa en: 24 Abril 2011, 17:00 pm
Un saludo para todos,

espero que alguien me pueda ayudar soy nuevo en el mundo de script y me gustaria aprender.

bueno mi pregunta es la siguiente. Tengo un servidor de impresoras con mas de 100  impresoras y lo migre a otro servidor, ahora necesito que los usuario se les mapee las impresoras al nuevo servidor, revisando encontre este script que lee desde un excel y mapea las impresoras, mi problema es como puedo cambiar la instruccion del excel para que me lea de una archivo CSV o TXT, adjunto el script para que alguien me pueda ayudar

si se puede reducir el codigo seria excelente.


Saludo

Código
  1. #############################################333
  2. Dim ObjNet,ObjGroup                                  
  3. Dim ComputerName,UserNamedim,CompType                
  4.  
  5. '###Fin declaración variables#####################################################################
  6.  
  7. '###creación objetos    
  8.  
  9. Set OBJnet = CreateObject("WScript.Network")           'crea el objeto net
  10.  
  11. '###fin creación objetos###########################################################################
  12.  
  13.  
  14. '####inicialización  variables#####################################################################
  15.  
  16.   ComputerName = ObjNet.ComputerName             'no necesita explicación...
  17.   UserName = ObjNet.username                     'coje el nombre
  18.  
  19.  
  20. '### fin de inicialización variables ##################################################################
  21.  
  22. '### MAIN ############################################################################################
  23.  
  24. if not existe then 'Comprueba que existe el fichero c:\temp\existe.txt. si no existe, es la primera vez que se ha entrado
  25.    WScript.Echo "User Name:        " & UserName
  26.    WScript.Echo "computername:     " & ComputerName
  27.    wscript.echo "tipo de máquina : " & tipoMaquina(ComputerName)'Por el tipo de letra del nombre, determina tipo de máquina.
  28.  
  29.     RemoveAllPrinters 'LAS BORRA TODAS BIEN BORRADAS.
  30.     wscript.echo excel
  31.    createafile 'crea el archivo para no ejecutar más el script.
  32. end if
  33.  
  34. '###END MAIN ############################################################################################
  35.  
  36.  
  37. '###FUNCIONES y RUTINAS ##############################################################################################
  38.  
  39. Function TipoMaquina(strcomputername)
  40. on error resume next
  41. CompType = ucase(mid(StrComputerName,6,1))                'determina que tipo de maquina es por la letra del nombre                                                                     'Desktop(D),Laptop(L) o server(0)
  42.         select case CompType
  43. case "D" TipoMaquina = "desktop"
  44. case "N" TipoMaquina = "Laptop"
  45. case "0" TipoMaquina= "servidor"
  46. case else TipoMaquina = "error"
  47.        end select
  48.  
  49. End Function
  50.  
  51.  
  52.  
  53. sub MapDrive(strDrive,strShare)                           'intenta mapear la unidad vía funcion y devuelve error false o true
  54. on error resume next                              ' si no se pone, para en el error y no comprueba el condicinoal del Err
  55. ObjNet.MapNetworkDrive strDrive,strShare
  56.        If Err  Then
  57. ObjNet.RemoveNetworkDrive strDrive
  58.               ObjNet.MapNetworkDrive strDrive,strShare
  59.        End If
  60. End sub
  61.  
  62.  
  63.  
  64. function  Getgroup(user,group) 'devuelve true or false dpendiendo si es del grupo o no. No hay otra manera de hacerlo
  65. Dim DomainName
  66. DomainName = "WinNT://MIDOMINIO/" 'cambiar al dominio propio.
  67.  
  68.          on error resume next
  69.  
  70.          Set ObjGroup = GetObject(DomainName &group)
  71.           if err then
  72.           wscript.echo "No existe el grupo : "&group
  73.           GetGroup = False
  74.           else
  75.               If ObjGroup.IsMember(DomainName&user) = true Then
  76.         wscript.Echo "si, pertenece al grupo "&group
  77.                     Getgroup = True
  78.               Else
  79.                 wscript.Echo "No pertenece al grupo "&group
  80.                 Getgroup = False
  81.                 End If
  82.                 end if
  83. end function
  84.  
  85. Function Excel
  86.  
  87. ArrayCols = Array ("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O","P","Q", "R", "S", "T", "U","V","W","X","Y","Z")
  88.                         'Define la tabla con letras, para hacer búsquedas secuenciales en el excel.
  89.  Dim libro
  90.  dim Intfil,Intcol
  91.  dim RutaExcel
  92.  RutaExcel = "\\RUTA_AL_EXCEL"
  93.  set libro = Wscript.CreateObject("Excel.Application")
  94.  call libro.Workbooks.Open(RutaExcel,0)
  95.  
  96.   libro.Sheets(1).Activate
  97.        Intcol = 0                                 'esto es un hack, para no declarar más veces la variable
  98. do
  99.                IntFil = 1
  100.                if Getgroup (Username,libro.Range(ArrayCols(Intcol) & Intfil).Text) = True then 'Comprueba si el usuario pertenece al grupo 'Recorre las columnas y luego las filas, comparando si es distinto de espacio en blanco, en caso negativo, si la fi
  101. Do while libro.Range(ArrayCols(Intcol) & Intfil+1).Text <>  ""
  102.                               wscript.echo "Instalando la impresora : " & libro.Range(ArrayCols(Intcol) & Intfil+1).Text & " espere... "
  103.                               Objnet.AddWindowsPrinterConnection libro.Range(ArrayCols(Intcol) & Intfil+1).Text  'instala impresora
  104.                               IntFil = IntFil + 1
  105. Loop
  106.                        intfil = 1 'Para volver a la primera fila otra vez y comparar
  107. end if
  108.                Intcol = Intcol + 1
  109. loop while  libro.Range(ArrayCols(Intcol) & Intfil).Text <> ""
  110.        libro.Quit 'IMPORTANTÍSIMOOOOOOOOO. es como los accesos via ADOdb. Se ha de cerrar conexion sino queda zombi
  111. end function
  112.  
  113. Function RemoveAllPrinters
  114. On Error Resume Next
  115. set objNetwork = CreateObject("wscript.network")
  116. Set objPrinters = objNetwork.EnumPrinterConnections
  117. For i = 0 to objPrinters.Count - 1 Step 2
  118.    PrinterPath = objPrinters.Item(i+1)
  119.    wscript.echo  "eliminando impresora : " & printerpath & " Espere..."
  120.    objNetwork.RemovePrinterConnection PrinterPath, true, true
  121. Next
  122.  
  123. end function
  124.  
  125. Function existe
  126. Dim Exist
  127.   Set Exist = CreateObject("Scripting.FileSystemObject")
  128.   If (Exist.FileExists("c:\temp\existe.txt")) Then
  129.    existe = True
  130.   Else
  131.     existe = False
  132.   End If
  133.  
  134. End Function
  135.  
  136.  
  137. Sub CreateAfile
  138.   Dim fso, MyFile
  139.   Set fso = CreateObject("Scripting.FileSystemObject")
  140.   Set MyFile = fso.CreateTextFile("c:\temp\existe.txt", True)
  141.   MyFile.Close
  142. End Sub
Páginas: [1]
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines