Archive for the ‘Scripts’ Category

Monitorando LOGON com vbs

Eu uso aqui no trabalho e funciona muito bem! Um amigo usou o mesmo script e colocou como script de logon e logoff.
Nas configurações de segurança de pastas concedo permissão ao usuário para somente alterar, e desmarco a opção excluir!

‘Inventario basico da Estação de Trabalho
‘Romeu –

strComputer = “.”
Set objWMIService = GetObject(“winmgmts:\\”& strComputer & “\root\cimv2”)

Set colSettings = objWMIService.ExecQuery (“Select * from Win32_ComputerSystem”)
Set colBIOS = objWMIService.ExecQuery (“Select * from Win32_BIOS”)
Set colDisks = objWMIService.ExecQuery (“Select * from Win32_LogicalDisk”)

Set IPConfigSet = objWMIService.ExecQuery (“Select IPAddress from Win32_NetworkAdapterConfiguration “)

Set oNetwork = CreateObject(“WScript.Network”)

‘Basta alterar o caminho UNC para onde vc queira armazenar os logs.
UNC = “\\caminho\invent$\”

strComputer = oNetwork.ComputerName
struser = oNetwork.UserName
systime = Now()
srtDay = cstr(day(systime))
strMonth = cstr(month(systime))
strYear = cstr(year(systime))
strTime = cstr(Time())
Const ForAppending = 8

For Each objComputer in colSettings
strManufac = objComputer.Manufacturer
strModel = objComputer.Model
strMemo = objComputer.TotalPhysicalMemory/1024000
Next

For each objBIOS in colBIOS
strSerial = objBIOS.SerialNumber
strBVersion = objBIOS.Version
Next

For Each strIPConfig in IPConfigSet
If Not IsNull(strIPConfig.IPAddress) Then
For i=LBound(strIPConfig.IPAddress) _
to UBound(strIPConfig.IPAddress)
‘WScript.Echo strIPConfig.IPAddress(i) &” – i=”& i
strIP0 = strIPConfig.IPAddress(0)
‘strIP1 = strIPConfig.IPAddress(1)

Next
End If
Next

For each objDisk in colDisks
strDiskTotal = objDisk.Size/1024
strDiskFree = objDisk.FreeSpace/1024
Next

Set fso = CreateObject(“Scripting.FileSystemObject”)

StrNew = UNC & strIP0 &”.log”

set sf=fso.OpenTextFile (StrNew, ForAppending, True)
sf.writeline “NOME DO HOST =” & strComputer & “; UserID =”& strUser &”; Date =”& srtDay &”-“& strMonth &”-“& strYear &”; Time =”& strTime & _
“; Manufacturer =” & strManufac & “; Model =”& strModel &”; Serial Number =”& strSerial & “; BIOS Version =:”& strBVersion & _
“; Memoria Fisica Total =”& strMemo &”; MAC ADDRESS =”& strMac & “; IP ADDRESS =”& strIP0 & _
“; Disk Size =”& strDiskTotal &”; Free Space =”& strDiskFree

Script para listar todos os arquivos de pastas de subpastas e gerar um indice em html

Infelizmente não fiz o script para ser executado diretamente a uma unidade de disco, pois  a pasta System Volume Information apresenta erro de acesso negado.
Escolha uma pasta e teste.
Caso alguém melhore o script avise que eu coloco a versão melhorada, ou coloco um link para a mesma.

'Script para listar todos os arquivos de pastas de subpastas e gerar um indice em html.
'Fonte:  http://www.tek-tips.com/viewthread.cfm?qid=1478950&page=9 e http://www.activexperts.com/activmonitor/windowsmanagement/scripts/storage/folders/
'Romeu Avancini rmavancini@gmail.com 23-11-2008

Set objFSO = CreateObject("Scripting.FileSystemObject")
Const ForAppending = 2
Const WINDOW_HANDLE = 0
Const NO_OPTIONS = 0
Set objShell = CreateObject("Shell.Application")

Set objFolderSelect = objShell.BrowseForFolder _
    (WINDOW_HANDLE, "Selecione a pasta onde será gravado o LOG:", NO_OPTIONS, " ")       
Set objFolderItemDest = objFolderSelect.Self
strEndFolder = objFolderItemDest.Path

LogFile = strEndFolder & "\index.html"
Dim objLogFile:Set objLogFile = objFSO.CreateTextFile(logfile, 2, True)

Set objFolderSelect = objShell.BrowseForFolder _
    (WINDOW_HANDLE, "Seleciona a pasta a ser gerado o relatorio:", NO_OPTIONS, " ")
Set objFolderItem = objFolderSelect.Self
objStartFolder = objFolderItem.Path

xFiles=0
xFolders=0
Set objFolder = objFSO.GetFolder(objStartFolder)
objLogFile.Write "<Font face='Arial' Color='Red'><b> Pasta Raiz : " & objFolder.Path & "</b></Font><br>"
objLogFile.Writeline "<Font face='Arial' Color='Red' size='5'>------------------------------------------------------------------------</Font><br>"
Set colFiles = objFolder.Files
For Each objFile in colFiles
	xFiles=xFiles+1
    objLogFile.Write  "<Font face='verdana' Color='black' size='2'><a href='" & objFolder.Path &"\"& objFile.Name & "'><b>" &  objFile.Name & "</b></a></Font><br>"
    objLogFile.Writeline
Next

ShowSubfolders objFSO.GetFolder(objStartFolder)

Sub ShowSubFolders(Folder)
    For Each Subfolder in Folder.SubFolders
		xFolders=xFolders+1
		objLogFile.Writeline "<Font face='Arial' Color='Red' size='5'>------------------------------------------------------------------------</Font><br>"
        objLogFile.Write "<Font face='Arial' Color='Red'><b>" &  Subfolder.Path & "</b></Font><br>"
		objLogFile.Writeline "<Font face='Arial' Color='Red' size='5'>------------------------------------------------------------------------</Font><br>"
        objLogFile.Writeline
        Set objFolder = objFSO.GetFolder(Subfolder.Path)
        Set colFiles =objFolder.Files
        For Each objFile in colFiles
			xFiles=xFiles+1
            objLogFile.Write "<Font face='verdana' Color='black' size='2'><a href='" & Subfolder.Path &"\"& objFile.Name & "'><b>" &  objFile.Name & "</b></a></Font><br>"
            objLogFile.Writeline
        Next
        ShowSubFolders Subfolder
    Next
End Sub

objLogFile.Writeline "<p>"
objLogFile.Write "<Font face='verdana' Color='blue' size='2'><a href=''><b>Dicas TI Blog</b></a></Font><br>"
objLogFile.Writeline "<Font face='verdana' Color='black' size='2'>" & xFiles & " arquivos nas " & xFolders & " pastas e subpastas!</font>"

objLogFile.Close
wscript.echo "Fim do script!"

wscript.quit

Script para criar vários usuarios no Active Directory.

Uma vez eu cheguei a fazer um vbs cheio de sacanagem para fazer isso! Importava usuários de uma planilha excel.
Bichu isso é muito mais simples. Veja abaixo criando usuários com o useradd usando um for.
Esse é o arquivo bat.
for /F “eol=; tokens=1,2,3,4* delims=,” %%i in (CadastroGeral.txt) do dsadd user “cn=%%i,ou=Temp,dc=meudominio,dc=local” -samid %%j -display %%k -pwd %%l -disabled yes -mustchpwd yes
Veja na imagem

Depois crie um arquivo texto com várias colunas com as informações que quer inserir, separe as colunas com virgula veja abaixo.

Meu nome,meulogin,”Meu nome completo”,minhasenha

Veja como o windows entende os parâmetros

O arquivo deve ter o mesmo nome que está entre parenteses no meu caso foi CadastroGeral.txt.

Muito show!
Entenda que você pode adcionar mais parâmetros do dsadd.
Quem me passou esse script foi o Ronil

Horario de verão 20008 / 20009

script para alterar horario de veão em estações de trabalho rodando windows 2k,XP e servidores com windows 2k e 2k3.
Infelizmente ao testar no vista ele altera o horário mas se reiniciar volta as configurações default.
Infelizmente não encontrei a pagina onde meu amigo Marcelo Dantas descobriu este script.

‘///////////////////////////////////////////////////////INICIO\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
‘script para alterar horario de verao no brasil
‘descoberto por Marcelo Dantas Bandeira – mdbandeira@gmail.com
‘alterado por Romeu Malacarne Avancini – rmavancini@gmail.com

Const BRASILIA_TZNAME = “E. South America Standard Time”
Const KEY_BRASILIA_TIME = “HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones\E. South America Standard Time”
Const KEY_TZINFO = “HKLM\SYSTEM\CurrentControlSet\Control\TimeZoneInformation”
Const REG_WINDOWSVERSION = “HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\CurrentVersion”

Dim strNewBrasiliaTZInfo, strNewDaylightStart, strNewStandardStart
Dim objShell, objFSO
Dim strCurrentStandardNameTZInfo
Dim intReturnValue
Dim strCurrentStandardName, strCurrentStandardNameSATime, strCurrentStandardNameSATimeMUI
Dim strRegExePath, intLastTZUpdate

On Error Resume Next

strNewBrasiliaTZInfo = “b400000000000000c4ffffff0000020000000300000000000000000000000a00000003000000000000000000”

strNewDaylightStart = “00000a00020000000000000000000000”

strNewStandardStart = “00000200030000000000000000000000”

Set objShell = CreateObject(“WScript.Shell”)
Set objFSO = CreateObject(“Scripting.FileSystemObject”)
Set objNetwork = CreateObject(“WScript.Network”)

intLastTZUpdate = 0

If LCase(objShell.Environment(“PROCESS”).Item(“OS”)) = “windows_nt” Then
    ‘Check if Timezone update was already applied. In this case, exit the script
    intLastTZUpdate = objShell.RegRead(KEY_BRASILIA_TIME & “\LastTZUpdate”)

    If intLastTZUpdate <> 2008 Then
      err.clear
      strRegExePath = getRegExePath
      If objFSO.FileExists(strRegExePath) Then
          ‘Set the registry key with the new Brasilia Timezone Information for 2008-2009
          intReturnValue = objShell.Run(strRegExePath & ” add ” & Chr(34) & KEY_BRASILIA_TIME & Chr(34) & _
                                          ” /v TZI /t REG_BINARY /d ” & _
                                        strNewBrasiliaTZInfo & ” /f”, 0, True)
          If (intReturnValue = 0) And (Err.Number = 0) Then
              ‘Check if the computer’s current time zone is (GMT -3:00) Brasilia time zone
              ‘If yes, change the current start and end daylight savings dates
              strCurrentStandardName = objShell.RegRead(KEY_TZINFO & “\StandardName”)
              strCurrentStandardNameSATime = objShell.RegRead(KEY_BRASILIA_TIME & “\Std”)
              strCurrentStandardNameSATimeMUI = objShell.RegRead(KEY_BRASILIA_TIME & “\MUI_Std”)
                                                         
              If ((Err.Number = 0) Or (Err.Number = -2147024894)) Then
                  If (LCase(strCurrentStandardName) = LCase(strCurrentStandardNameSATime)) Or _
                       (LCase(strCurrentStandardName) = LCase(strCurrentStandardNameSATimeMUI)) Then
                      ‘The current time zone is (GMT -3:00) Brasilia time zone
                      ‘Update current time zone information with the new settings
                      err.clear
                      intReturnValue = objShell.Run(strRegExePath & ” add ” & Chr(34) & KEY_TZINFO & Chr(34) & _
                                                  ” /v DaylightStart /t REG_BINARY /d ” & _
                                                  strNewDaylightStart & ” /f”, 0, True)
                                                               
                      intReturnValue = intReturnValue + objShell.Run(strRegExePath & ” add ” & Chr(34) & KEY_TZINFO & Chr(34) & _
                                                  ” /v StandardStart /t REG_BINARY /d ” & _
                                                  strNewStandardStart & ” /f”, 0, True)
                                                                                                                                       
                      If (intReturnValue = 0) And (Err.Number = 0) Then
                          ‘TimeZone information set fine
                          ‘We only need to update the current setting
                          If wscript.Version < “5.7” Then
                            objShell.Run “CONTROL.EXE TIMEDATE.CPL,,/Z ” & BRASILIA_TZNAME, 0, True
                          End If
                          lineOut “Time zone for 2007-2008 (GMT -3:00) Brasilia time zone updated successfully.” & vbCrLf & _
                                  “Current time zone for 2007-2008 updated successfully.”, 0
                          ‘Save a registry key to avoid refreshing timezone running script each startup.
                          objShell.RegWrite KEY_BRASILIA_TIME & “\LastTZUpdate”, 2007
                      Else
                          ‘Reg.exe returned an error
                          lineOut “An error occurred when updating current time zone information”, 2
                      End If
                  Else
                    lineOut “Current standard time zone is ‘” & strCurrentStandardName & “‘. No need to update it. ” & vbCrLf & _
                            “(GMT -3:00) Brasilia time zone information for 2007-2008 updated successfully.”, 0
                    ‘Save a registry key to avoid refreshing timezone running script each startup.
                    objShell.RegWrite KEY_BRASILIA_TIME & “\LastTZUpdate”, 2007
                  End If
              Else
                  ‘Error querying time zone information
                  lineOut “An error occurred querying the time zone information”, 2
              End If
             
          Else
              ‘ An error occurred when you set the Time Zone information for Brasilia Time
              lineOut “An error occurred when updating time zone information for (GMT -3:00) Brasilia”, 2
          End If
      Else
          lineOut “Could not find reg.exe in following location: ” & strRegExePath & vbCrLf & _
                  “(GMT -3:00) Brasilia time zone for 2007-2008 not updated”, 2
      End If
   End If
Else
    lineOut “Operating System not Supported. Run the script in a Windows NT-based operating system.”, 1
End If

Function getRegExePath()
    ‘Windows 2000 does not have inbox reg.exe. In this case,
    ‘we need to make sure reg.exe is present on the same folder as script is located.
      getRegExePath = objFSO.GetSpecialFolder(1) & “\reg.exe”
      If Not objFSO.FileExists(getRegExePath) Then
          getRegExePath = objFSO.GetParentFolderName(wscript.ScriptFullName) & “\reg.exe”
      End If
End Function

Sub lineOut(strLine, intType)
    Dim ScriptHost
    ScriptHost = wscript.FullName
    ScriptHost = Right(ScriptHost, Len(ScriptHost) – InStrRev(ScriptHost, “\”))
   
    If (InStr(1, wscript.FullName, “CSCRIPT.EXE”, 1) > 0) Then
        wscript.Echo strLine
    Else
        ‘Do not display anything if not running under cscript command line processor.
        ‘If you want to have a message box that contains the message,
        ‘remove the ‘ for the line under
        ‘wScript.Echo stLine
    End If
    objShell.LogEvent intType, strLine
End Sub

wscript.quit

‘///////////////////////////////////////////////////////FIM\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

Apagar arquivos antigos de uma determinada pasta

Esta semana atendi um cliente que tinha problemas de arquivos temporários ocupando muito espaço em disco.
Criei um script em vbs que executa uma ferramenta gratuita.
Obs: Tenho um script todo em vbs que faz a mesma coisa, mas para a realidade do meu cliente esta foi a melhor alternativa.

‘//////////////////////////////INICIO////////////////////////////////////////////
‘Script para executar o purger e limpar arquivos em locais especificos
‘Autor: Romeu Malacrne Avancini – – rmavancini@gmail.com
‘ Versão 1.2
‘Data 04/07/2008
‘Você vai precisar de fazer o download do purger (ftp://ftp.sac.sk/pub/sac/utilfile/purger.zip )
‘Copie o purger para uma pasta, sysvol ou netlogon, ou para uma pasta compartilhada da rede
‘Insira o caminho onde está o purger, usando caminho UNC
strPath = “D:\Romeu\Scripts”

‘Criação do objetos
Set objFSO = CreateObject(“Scripting.FileSystemObject”)
Set objNetwork = CreateObject(“WScript.Network”)
Set WshShell = WScript.CreateObject(“WScript.Shell”)
‘set objEnvironment = WshShell.Environment(“user”)
‘strTMPVar = objEnvironment(“temp”)

strUserName = objNetwork.UserName
‘strComputerName = objNetwork.ComputerName

strComputer = “.”
‘wscript.echo strTMPVar

‘Deleta arquivos na pasta temp do peril do usuário
‘Está configurado para apagar arquivos na pasta temp do usuário do windows Vista, caso seja outra pasta altere o caminho.
‘A variavel strUserName faz referencia ao nome de usuário da rede.
subDelFiles (“C:\Users\”& strUserName &”\Configurações locais\Temp”)

‘sub procedure executa a limpeza das pasta temp apagando arquivos que estão a mais de 15 dias no local
Sub subDelFiles(strDest)
If objFSO.FolderExists(strDest) Then
WshShell.run “CMD.EXE /C attrib -r -a -s -h “& strDest &”\*.* /s /d”
‘aqui é o comando onde precisa clocar a quantidade de dias de vida do arquivo
WshShell.run strPath & “\PURGER.EXE -rde 15 “& strDest &”\*.*”
WshShell.run “CMD.EXE /C echo “& now &”> “& strDest &”\DELETAR.txt”
‘Wscript.echo “Entrou no IF e chegou ao fim”
Else
‘Wscript.echo “Entrou no Else! O if não foi verdadeiro”
End If
End Sub

Wscript.Quit
‘\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\FIM\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

Script para pingar num range de IP

Entre com o ip inicial e final que ele gera uma lista de maquinas que responderam ao ping.

Obs:

Na linha 64 modifique o caminho do arquivo temporário;

Na 68 modifique o caminho do arquivo xls

‘º MultiPing.vbs v2.0 º
‘º º
‘º Script to ping a range of IP Addresses and º
‘º write results to an Excel Workbook º
‘º º
‘º Noel McGran (23/07/04) º

‘User Input of IP range
Message = “Please enter start IP:”
Title = “Start Range”
StartIP = InputBox(Message, Title)
xx = StartIP
Good = ValidIP(xx)

Do while Good = “invalid”
Message = StartIP & ” is not a valid IP.” & _
vbCrLf & “Please re-enter start IP:”
Title = “Start Range”
StartIP = InputBox(Message, Title)
xx = StartIP
Good = ValidIP(xx)
Loop

Message = “Please enter end IP:”
Title = “End Range”
EndIP = InputBox(Message, Title)
yy = EndIP
Good = ValidIP(yy)

Do while Good = “invalid”

Message = EndIP & ” is not a valid IP.” & _
vbCrLf & “Please re-enter end IP:”
Title = “End Range”
EndIP = InputBox(Message, Title)
yy = EndIP
Good = ValidIP(yy)
Loop

xx = StartIP
yy = EndIP

Good = GreaterIP(xx,yy)

Do while Good = “before”

Message = EndIP & ” is ” & Good & ” ” & StartIP _
& vbCrLf & “Please re-enter End IP:”
Title = “End Range”
EndIP = InputBox(Message, Title)
xx = StartIP
yy = EndIP
Good = GreaterIP(xx,yy)
Loop

msgText = “IP range is ” & StartIP & ” to ” & EndIP _
& vbCrLF & “Continue?”

Select Case MsgBox(msgText, VBOKCancel)

Case 1

TempFilename = “D:\Romeu\Scripts\tmp\IPtemp.txt”
notfound = “No Response”

‘ Spreadsheet file to be created.
strExcelPath = “D:\Romeu\Scripts\tmp\MultiPing.xls”

‘ Bind to Excel object.
Set objExcel = CreateObject(“Excel.Application”)

‘ Create a new workbook.
objExcel.Workbooks.Add

‘ Bind to worksheet.
Set objSheet = objExcel.ActiveWorkbook.Worksheets(1)
objSheet.Name = “Active IPs”

‘ Populate spreadsheet cells with user attributes.
objSheet.Cells(1, 1).Value = “IP Address”
objSheet.Cells(1, 2).Value = “Computer Name”

‘ Format the spreadsheet.
objSheet.Range(“A1:B1”).Font.Bold = True
objSheet.Select
objSheet.Range(“A2:B2”).Select
objExcel.ActiveWindow.FreezePanes = True
objExcel.Columns(1).ColumnWidth = 15
objExcel.Columns(2).ColumnWidth = 30

LF = chr(10)
const ForReading = 1, ForWriting = 2, ForAppending = 3

currentIP = StartIP
set shell = CreateObject (“wscript.shell”)
Set FS = CreateObject (“scripting.FileSystemObject”)

j = 2

Do

command = “cmd /C ping -a ” & currentIP & ” > ” _
& TempFilename
x = shell.run(command, 0, true)
set f = fs.OpenTextFile(tempfilename, ForReading, true)
fline = f.readline
fline = f.readline

l1 = instr (fline, ” “)
l2 = instr (fline, “[“)
if l2 = 0 then
mname = notfound
else
mname = mid (fline, l1, l2-l1)
end if

objSheet.Cells(j, 1).Value = currentIP
objSheet.Cells(j, 2).Value = mname

f.close
xx = currentIP
currentIP = newIP(xx)
j = j+1

Loop Until currentIP = EndIP

‘ process last IP
command = “cmd /C ping -a ” & currentIP & ” > ” _
& TempFilename
x = shell.run(command, 0, true)
set f = fs.OpenTextFile(tempfilename, ForReading, true)
fline = f.readline
fline = f.readline

l1 = instr (fline, ” “)
l2 = instr (fline, “[“)
if l2 = 0 then
mname = notfound
else
mname = mid (fline, l1, l2-l1)
end if

objSheet.Cells(j, 1).Value = currentIP
objSheet.Cells(j, 2).Value = mname

f.close

‘ Save the spreadsheet and close the workbook.
objExcel.ActiveWorkbook.SaveAs strExcelPath
objExcel.ActiveWorkbook.Close

‘ Quit Excel.
objExcel.Application.Quit

‘ Clean Up
Set objSheet = Nothing
Set objExcel = Nothing

wscript.echo “Done!”

Case 2
wscript.echo “Goodbye.”
Set objSheet = Nothing
Set objExcel = Nothing

End Select

‘————
‘function for increasing the IP number
‘————
function newip(xx)
dim n,n1,n2,n3,n4,v1,v2,v3,v4
n = 1
n0 = n

while mid (xx,n,1) “.”
n = n+1
wend

n1 = n
n = n+1

while mid (xx,n,1) “.”
n = n+1
wend

n2 = n
n = n+1

while mid (xx,n,1) “.”
n = n+1
wend

n3 = n
n4 = len(xx)
v1 = mid (xx,n0,n1-1)
v2 = mid (xx,n1+1,n2-n1-1)
v3 = mid (xx,n2+1,n3-n2-1)
v4 = mid (xx,n3+1,n4-n3)
v4 = v4+1

if v4 > 255 then
v3 = v3+1
v4 = 0
end if

if v3 > 255 then
v2 = v2+1
v3 = 0
v4 = 0
end if

if v2 > 255 then
v1 = v1+1
v2 = 0
v3 = 0
v4 = 0
end if

return = (v1 & “.” & v2 & “.” & v3 & “.” & v4)
newIP = return
end function

‘————
‘function for validating the IP address
‘————
function ValidIP(xx)

dim n,n0,n1,n2,n3,n4,v1,v2,v3,v4,s,s1,s2,s3,s4
n = 1
n0 = n
s = 1
return = “valid”

s1 = InStr(s, xx, “.”, 1)
s2 = InStr(s1+1, xx, “.”, 1)
s3 = InStr(s2+1, xx, “.”, 1)
s4 = len(xx)+1

if s1-s 3 then
return = “invalid”
elseif s2-s1 4 then
return = “invalid”
elseif s3-s2 4 then
return = “invalid”
elseif s4-s3 4 then
return = “invalid”
else
while mid (xx,n,1) “.”
n = n+1
wend

n1 = n
n = n+1

while mid (xx,n,1) “.”
n = n+1
wend

n2 = n
n = n+1

while mid (xx,n,1) “.”
n = n+1
wend

n3 = n
n4 = len(xx)
v1 = mid (xx,n0,n1-1)
v2 = mid (xx,n1+1,n2-n1-1)
v3 = mid (xx,n2+1,n3-n2-1)
v4 = mid (xx,n3+1,n4-n3)

if v4 > 255 then
return = “invalid”
end if

if v3 > 255 then
return = “invalid”
end if

if v2 > 255 then
return = “invalid”
end if

if v1 > 255 then
return = “invalid”
end if
end if

ValidIP = return

end function

‘————
‘function for validating the End IP address
‘————
function GreaterIP(aa,zz)

return = “after”

dim n,n0,n1,n2,n3,n4,v1,v2,v3,v4
dim m,m0,m1,m2,m3,m4,w1,w2,w3,w4

n = 1
n0 = n

while mid (xx,n,1) “.”
n = n+1
wend

n1 = n
n = n+1

while mid (xx,n,1) “.”
n = n+1
wend

n2 = n
n = n+1

while mid (xx,n,1) “.”
n = n+1
wend

n3 = n
n4 = len(xx)
v1 = mid (xx,n0,n1-1)
v2 = mid (xx,n1+1,n2-n1-1)
v3 = mid (xx,n2+1,n3-n2-1)
v4 = mid (xx,n3+1,n4-n3)

m = 1
m0 = m

while mid (yy,m,1) “.”
m = m+1
wend

m1 = m
m = m+1

while mid (yy,m,1) “.”
m = m+1
wend

m2 = m
m = m+1

while mid (yy,m,1) “.”
m = m+1
wend

m3 = m
m4 = len(yy)
w1 = mid (yy,m0,m1-1)
w2 = mid (yy,m1+1,m2-m1-1)
w3 = mid (yy,m2+1,m3-m2-1)
w4 = mid (yy,m3+1,m4-m3)

if cint(v1) > cint(w1) then
return = “before”
else
if cint(v2) > cint(w2) then
return = “before”
else
if cint(v3) > cint(w3) then
return = “before”
else
if cint(v4) > cint(w4) then
return = “before”
end if
end if
end if
end if

GreaterIP = return

end function

Livro de WSH gratuito

A editora Novatec está disponobilizando gratuitamente o livro Windows Script Host – Guia de Consulta Rápida.

É um bom material de consulta.

http://www.novateceditora.com.br/ebooks/

Script em vbs gera uma lista dos usuários logados em qual computador

Esta semana precisei de um script que me mostrasse qual usuário estava logado em qual estação de trabalho da rede.
Pesquisando an internet achei este aqui no forum do Mark Minasi(é o cara do windão)
http://x220.minasi.com/forum/post.asp?method=TopicQuote&TOPIC_ID=3301&FORUM_ID=30
Você precisa criar um arquivo txt com as maquinas que você quer obter o resultado.
O script gera uma lista com os seguintes resultados.
hostname: Domain\username -> Encontrou o usuário
hostname: Host Unreachable -> Não encontrou o host
hostname: No user -> Não existe usuario logado atualmete.

Segue script abaixo.
Por favor não retire os créditos do desenvolvedor.

‘********************************************************************
‘* File: GetUser.vbs
‘* Created: November 2003
‘* Version 1.0
‘*
‘* Main Function: Retrieves current logged on user name for computer
‘* names from input file named compname.txt
‘* Results are written to a log file
‘*http://x220.minasi.com/forum/post.asp?method=TopicQuote&TOPIC_ID=3301&FORUM_ID=30
‘*
‘********************************************************************

Option Explicit

Dim sDate
Dim strTime
Dim strDate
Dim strDataIn ‘Input list from text file
Dim aryData ‘Array to hold input stream
Dim iCounter ‘Iterative loop counter
dim strOUT ‘Output file
Dim oWshShell ‘Windows shell script
Dim objFSO ‘Scripting File System
Dim objFile ‘Open text file
Dim strFilePath ‘Path to current directory
Dim strPCName ‘Computer names extracted for input file
Dim strRet

Set oWshShell = CreateObject(“WScript.Shell”)
Set objFSO = CreateObject(“Scripting.FileSystemObject”)
strFilePath = objFSO.GetAbsolutePathName(“.”)

‘First step: read file into a variable
strDataIn = f_r(strFilePath & “\compname.txt”)

aryData = Split(strDataIn,vbCrLf) ‘ this creates an array

oWshShell.Popup Ubound(aryData) + 1 & ” Hosts/Addresses in list.” & Chr(13) & “User query is underway.”,2,”Notice”,64
sDate = Date
strTime = Now
StrDate = DatePart(“m”,sDate) & “.” & DatePart(“d”,sDate) & “.” & Hour(strTime) & “.” & Minute(strTime)
set strOUT = objFSO.CreateTextFile(strFilePath & “\UsernameResults.” & strDate & “.log”)

For iCounter = 0 to Ubound(aryData)
aryData(iCounter) = Trim(aryData(iCounter)) ‘ clean “white space”
strPCName = GetUsr(aryData(iCounter))
strOUT.Write aryData(iCounter) & “: ” & strRet & vbcrlf

Next

strOUT.Close

set strOUT = nothing
set objFSO = nothing

oWshShell.Popup “Processing complete.”,5,”Notice”,64

wscript.quit

‘********************************************************************************
‘* Function f_r(FilePath) *
‘* *
‘* Given the path to a file, this function will return entire contents *
‘* *
‘********************************************************************************

Function f_r(FilePath)
Dim FSO
set FSO = CreateObject(“Scripting.FileSystemObject”)

f_r = FSO.OpenTextFile(FilePath,1).ReadAll

End Function

Function GetUsr(strComputerName)

Dim WMIServices
Dim objUserSet
Dim User

WMIServices = “winmgmts:{impersonationLevel=impersonate}!//”& strComputerName &””

On Error Resume Next
Set objUserSet = GetObject( WMIServices ).InstancesOf (“Win32_ComputerSystem”)

If Err.number 0 Then

If Err.Number = “-2147217405” Then

strRet = “Access Denied”

ElseIf Err.Number = “462” Then

strRet = “Host Unreachable”

Else

strRet = “Computer does not respond. “

End If

Else

for each User in objUserSet

If User.UserName “” Then

strRet = User.UserName

Else

strRet = “No user”

End If

Next

End If

End Function