Solved

Vb Script, to copy particular folder with subdirectories from multiple servers to a common location with unique server names as their respective folders

Posted on 2008-06-15
9
2,919 Views
Last Modified: 2013-12-09
i have to copy PKI folder from Remote servers, i hav admin access, so when do \\servername i can copy the contents of VPHOME folder.  For ur easy understanding, i can tell u, PKI is a certification file of Symantec Antivirus Servers, each server is having a share named VPHOME, inside VPHOME share, u may find, Grc.dat file, and a folder name PKI, inside PKI u have subdirectories and files.




d:                                                        "The backup files of remote server should be in D drive of the master server, im running the code from"
cd\
cd NewPKI                                            "Folder to backup the PKI contents"
cd ServerGroupName                        "ServerName to be replaced everytime it runs"
md ServerName                                    "Need to create a directory in the name of the server it replaces"
cd ServerName                                            "Changing the directory to the respective servername folder for backup of PKI folder"
copy \\ServerName\VPHOME\grc.dat        " in the server share, u have VPHOME as share, from which i hav to backup GRC.DAT file alone"
Xcopy \\ServerName\VPHOME\pki /E /Y            " Inside PKI folder, u may have 4 subdirectories, several files of some 10 to 20 Kb files"


In the above code, the ServerName need to be replaced with the name of the servers in the list of CSV / Txt  file.

in the CSV/txt file, u may have the server names like this.

S.No.        ServerName        ServerGroupName

1                JSBXXX                ASIA
2.             HSBDYU                ASIA
3.            FFSSLF                ASIA
4.            DFLSSF                ASIA

After we run a script, the folder map will b like this
D:\NewPki\Asia\JSBXXX\PKI\...\..
D:\NewPki\Asia\HSBDYU\PKI\...\..
D:\NewPki\Asia\FFSSLF\PKI\...\..
D:\NewPki\Asia\DFLSSF\PKI\...\..

going further, the servergroupname also changes, like consider it as location based. such as America. We have to create seperate folder for America as     d:\NewPKI\America\....., the servernames will b different in that location.
--

P.S. I have gone thru this http://www.experts-exchange.com/Programming/Languages/Scripting/Shell/Batch/Q_22612350.html?sfQueryTermInfo=1+copi+file+from+remot+script+server thread, but it only concentrates on Log files, so i dont know how to convert them for my PKI folders in VB script.

pls help me; My mail id shankjai@yahoo.com
cd\

cd NewPKI                                            "Folder to backup the PKI contents"

cd ServerGroupName                        "ServerName to be replaced everytime it runs"

md ServerName                                    "Need to create a directory in the name of the server it replaces"

cd ServerName                                            "Changing the directory to the respective servername folder for backup of PKI folder"

copy \\ServerName\VPHOME\grc.dat        " in the server share, u have VPHOME as share, from which i hav to backup GRC.DAT file alone"

Xcopy \\ServerName\VPHOME\pki /E /Y            " Inside PKI folder, u may have 4 subdirectories, several files of some 10 to 20 Kb files"

Open in new window

0
Comment
Question by:shankjai
  • 5
  • 2
9 Comments
 
LVL 25

Expert Comment

by:Ron M
Comment Utility
I don't see why this has to be vb script... any particular reason you don't want to use xcopy ?

example ...
xcopy "\\JSBXXX\vphome\*.*" "d:\NewPKI\asia\JSBXXX\vphome\*.*" /D /E /I /R /Y

also, have you considered creating a single batch file to be run as a scheduled task from all servers ?..as opposed to maintaining a script when you have to add and remove servers...

first you set a global environment variable on every server...using this code as a startup script...
This creates a permanent system variable you can use to identify the subnet a server is on, and use it as a variable.
http://www.microsoft.com/technet/scriptcenter/csc/scripts/desktop/settings/cscds060.mspx

example batch script to run on any remote server..

IF %NETID% == 172.16.9 xcopy "\\%computername%\VPhome\*.*" "\\pkiserver\vphome\ASIA\%computername%\NewPKI\*.*" /D /E /I /R /Y
IF %NETID% == 172.16.10 xcopy "\\%computername%\VPhome\*.*" "\\pkiserver\vphome\AMERICA\%computername%\NewPKI\*.*" /D /E /I /R /Y
IF %NETID% == 172.16.11 xcopy "\\%computername%\VPhome\*.*" "\\pkiserver\vphome\MEXICO\%computername%\NewPKI\*.*" /D /E /I /R /Y

let me know what you think...
0
 
LVL 25

Expert Comment

by:Ron M
Comment Utility

IF %NETID% == 172.16.9 xcopy "\\%computername%\VPhome\*.*" "\\pkiserver\vphome\ASIA\%computername%\NewPKI\*.*" /D /E /I /R /Y

IF %NETID% == 172.16.10 xcopy "\\%computername%\VPhome\*.*" "\\pkiserver\vphome\AMERICA\%computername%\NewPKI\*.*" /D /E /I /R /Y

IF %NETID% == 172.16.11 xcopy "\\%computername%\VPhome\*.*" "\\pkiserver\vphome\MEXICO\%computername%\NewPKI\*.*" /D /E /I /R /Y

Open in new window

0
 

Author Comment

by:shankjai
Comment Utility
Option Explicit

Dim strFile, objSh , errorFile, objErr1
Dim  strSrc1, strSrc2, strDest, bolFlag

'Enter the Server name into the Computers.txt file, one entry per line
strFile = "SymantecPSList.txt"

Dim objFSO, objTS, strComputer, objOuts, objFolder, objErr, objFile, i,strLine, objPing, objStatus,colComputer, oComputer
Dim iDR, sName

'specify filename and folder path for file/folder to be copied



strSrc1="\vphome\pki"
strSrc2 = "\vphome\grc.dat"




'specify target destination
strDest="\\mainserver\Final\New Folder\ "



Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objSh = CreateObject("WScript.Shell")

'Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("SymantecPSList.txt", ForReading)
Const ForReading = 1
Const ForAppending = 8
 
Dim arrFileLines()
i = 0
Do Until objFile.AtEndOfStream
    Redim Preserve arrFileLines(i)
    arrFileLines(i) = objFile.ReadLine
    i = i + 1
Loop
objFile.Close
 
'     Set objFSO = CreateObject("Scripting.FileSystemObject")
'     Set objSh = CreateObject("WScript.Shell")
    If objFSO.FileExists("output.txt") Then
 
    Else
       Set objFile = objFSO.CreateTextFile("output.txt")
    End If
   
    Set objFile = Nothing
   

''Checks whether Server list is available
If objFSO.FileExists(strFile) Then
   
    Set objFile = objFSO.OpenTextFile("output.txt", ForAppending)
   
    objFile.WriteLine("---------------------------------------------------------------------------------------------")
    objFile.WriteLine("Ping Results of the Servers in the server List as on  " & now())
    objFile.WriteLine("______________________________________________________________________________________________")
    objFile.WriteLine("")
   
' For Each strLine in arrFileLines
'    Set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}")._
'        ExecQuery("select * from Win32_PingStatus where address = '"_
'            & strLine & "'")
'    For Each objStatus in objPing
'        If IsNull(objStatus.StatusCode) or objStatus.StatusCode<>0 Then
'            objFile.WriteLine("Server: " & strLine & " is not reachable" & vbTab & objStatus.ProtocolAddress)
'        Else
'            objFile.WriteLine("Server: " & strLine & " is reachable *********************"& vbTab & objStatus.ProtocolAddress)
'
'For Each strLine in arrFileLines
'WScript.Echo ResolveIP("strLine")
'
'Function ResolveIP(strComputer)
''     On Error Resume Next
'
'    Dim wmiQuery, objWMIService, objPing, objStatus
'    
'    wmiQuery = "Select * From Win32_PingStatus Where " & _
'    "Address = '" & strComputer & "'"
'    
'    Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
'    Set objPing = objWMIService.ExecQuery(wmiQuery)
'    
'    For Each objStatus in objPing
'        If IsNull(objStatus.StatusCode) Or objStatus.Statuscode<>0 Then
'            ResolveIP = "Computer is Unreachable!"
'        Else
'            ResolveIP = objStatus.ProtocolAddress
'        End If
'    Next
'End Function
'
'Next
For Each strLine in arrFileLines
If Reachable("strLine") Then
    WScript.Echo "Computer" & strLine & "is Reachable"
Else
    WScript.Echo "Computer is Unreachable!"
End If

Function Reachable(strComputer)
'     On Error Resume Next

    Dim wmiQuery, objWMIService, objPing, objStatus
   
    wmiQuery = "Select * From Win32_PingStatus Where " & _
    "Address = '" & strComputer & "'"
   
    Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
    Set objPing = objWMIService.ExecQuery(wmiQuery)
   
    For Each objStatus in objPing
        If IsNull(objStatus.StatusCode) Or objStatus.Statuscode<>0 Then
            Reachable = False 'if computer is unreacable, return false
        Else
            Reachable = True 'if computer is reachable, return true
        End If
    Next
End Function


'Set colComputer = GetObject("winmgmts:\\" & strLine & "\root\cimv2").ExecQuery("Select DomainRole, Domain from Win32_ComputerSystem")
'For Each oComputer in colComputer
'iDR = oComputer.DomainRole
'sName = oComputer.Domain
'Next
'
'If iDR = 0 Or iDR = 2 Then
'objFile.WriteLine "Computer is in workgroup " & sName
'Else
'objFile.WriteLine "Computer is in domain " & sName
'End If
 
        End If
    Next
Next
       
End If
' objFile.Close

Set objFile = Nothing

WScript.Echo "****************************************************************************"
WScript.Echo "PKI Folder  Backup in progress, Please wait till the program says 'COMPLETE'"
WScript.Echo "****************************************************************************"
WScript.Echo ""
    Set objTS = objFSO.OpenTextFile(strFile)
    Set objOuts = objFSO.CreateTextFile("PKIbackupServerList.txt")
    Set objErr = objFSO.CreateTextFile("ErrorList.txt")            
   
    objOuts.WriteLine("---------------------------------------------------------------------------------------------")
    objOuts.WriteLine("List of Server Names whose PKI backup was done successfully on  " & now())
    objOuts.WriteLine("______________________________________________________________________________________________")
    objOuts.WriteLine("")
   
    objErr.WriteLine("---------------------------------------------------------------------------------------------")
    objErr.WriteLine("List of Server Names whose PKI backup was not done as on  " & now())
    objErr.WriteLine("______________________________________________________________________________________________")
    objErr.WriteLine("")
   
Do Until objTS.AtEndOfStream
        strComputer = objTS.ReadLine

'Folder created with the respective server names    
'        If objFSO.FolderExists("\\mainserver\Final\New Folder\" & strComputer) Then

Set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}")._
        ExecQuery("select * from Win32_PingStatus where address = '"_
            & strComputer & "'")
 For Each objStatus in objPing
    If IsNull(objStatus.StatusCode) or objStatus.StatusCode<>0 Then
            objErr.WriteLine("Server: " & strComputer & " is not reachable" & vbTab & objStatus.ProtocolAddress)
    Else
            objOuts.WriteLine("Server: " & strComputer & " is reachable *********************"& vbTab & objStatus.ProtocolAddress)
                     'End If
                     'Next
                    If objFSO.FolderExists("D:\NewPki" & strComputer) Then
           
                            WScript.Echo "Folder " & strComputer & " already exists, Skipping the server"
                            '    objErr.WriteLine("Server: " & strComputer & " is reachable *********************" & vbTab & objStatus.ProtocolAddress)
   
                         'Server list which are skipped.
                             objErr.WriteLine ("Server Name: " & strComputer & " Folder already exists hence skipped PKI backup")
                             objErr.WriteLine("Server: " & strComputer & " is reachable *********************"& vbTab & objStatus.ProtocolAddress)
                             
             
                    Else
               
                        Set objFolder    = objFSO.CreateFolder(strComputer)
                            'PKI folders are copied along with GRC.dat file in the created server folders    
                        '            objSh.Run "Xcopy.exe \\" & strComputer & "\Share\Test " & " " & "\\mainserver\Final\New Folder\" & strComputer & " /e /y"
                        '            objSh.Run "Xcopy.exe \\" & strComputer & "\test2\sam.cab" & " " & "\\mainserver\Final\New Folder\" & strComputer & "  /y"
                                   
'                                    objSh.Run "Xcopy.exe " & strSrc1 & " " & strDest & strComputer & " /e /y"
'                                    objSh.Run "Xcopy.exe " & strSrc2 & " " & strDest & strComputer & "  /y"
                        '            
                        ' '             objSh.Run "Xcopy.exe C:\test C:\Backup /E /Y"
                                   
                                objSh.Run "Xcopy.exe \\" & strComputer & strSrc1 & " " & strDest & "\" & strComputer & " /e /y"
                                objSh.Run "Xcopy.exe \\" & strComputer & strSrc2 & " " & strDest & "\" & strComputer & "  /y"
                        '            objSh.Run "Xcopy.exe \\mainserver\test" & " " &  "\\mainserver\Final\New Folder"  & " /e /y"
                           
                        '         WScript.Echo "Tried the above link for " & strComputer
                        WScript.Echo "Folder Created in the Name of :" & strComputer
                       
                                    objOuts.WriteLine ("PKI Backup done for the Server Name: " & strComputer)
               
                    End If
    End If

Next

Loop


   

'    End If

objTS.Close
 objOuts.Close
 objErr.Close    
 'objFile.Close


WScript.Echo "output of Backup servers will be in PKIbackupServerList.txt file"
WScript.Echo "output of skipped servers will be in ErrorList.txt file"



WScript.Echo
WScript.Echo "Complete :o)"


0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 

Author Comment

by:shankjai
Comment Utility
The above code i fixed and run it in my server, its working. but the query state in the above code "'Set colComputer = GetObject("winmgmts:\\" & strLine & "\root\cimv2").ExecQuery("Select DomainRole, Domain from Win32_ComputerSystem")" throws error while run in windows 2003 environment. hence i commented the Ping status codes.

any idea how to check, whether the server is reachable, if reachable output the IP address and hostname of the server which are done with PKI backup.

P.S. For your question about the schedule backup on servers. The network is huge n the servers are large. any change in the schedule task has to go through proper procedure. this will take a month or two to proceed. I dont want the management to involve in approval / query. thats y i would like to run a vbscript with the list of server names in my network. Moreover, a copy of PKI folder for each server is enough, no need to take the backup again and again as scheduled.
0
 
LVL 25

Accepted Solution

by:
Ron M earned 50 total points
Comment Utility
while the above code is robust...obviously shankjai put alot of work into it... the problem with vb is that it doesn't wait for a command to complete before running the next line of code.  Also, if the return code is 0 vb assumes everything is peaches..The command executed, but it doesn't mean it succeeded.  

Essentially the above code is using VB, to run command line arguments ( xcopy ! ), ....which is why I think you would be better off using a simple batch file and just "do the deed" without complicating it by querying WMI and having to constantly debug a large vb script everytime you need to make a change or add/remove a server or directory or whatever...

You'll notice with WMI and vb, you'll get varying results from server to server as well.

You can run the batch file (xcopy) from your own machine as long as you have admin rights...  putting it as a scheduled task on each server was just a suggestion.

To check if a server is online...and that you have admin rights..  is simple.  Just look for the presence of a file...any file in the administrative share. C$..and also keep a log of whether or not copying succeeded.

EXAMPLE:

:1
IF NOT EXIST == \\servername1\c$\windows\system32\explorer.exe GOTO 2
xcopy \\servername1\pki\*.* \\servername2\PKI\USA\servername1\*.* /D /E /I /R /Y
GOTO 3
:2
ECHO servername1 not online %date% %time% >> \\servername2\pki\logfile.txt
:3
IF NOT EXIST == \\servername3\c$\windows\system32\explorer.exe GOTO 4
xcopy \\servername1\pki\*.* \\servername2\PKI\Asia\servername1\*.* /D /E /I /R /Y
GOTO 5
:4
ECHO servername3 not online %date% %time% >> \\servername2\pki\logfile.txt
:5
etc.....
the above example servername2 is the repository server..

VB is good for alot of things.. but the simple copying of files from one location to another...is not one of them.  You can write a batch file to do the same thing in a fraction of the time.
0
 
LVL 25

Expert Comment

by:Ron M
Comment Utility
I guess if you have the code working...and you just want to see if a machine is online. Use the code below.  Of course sub strComputer for strHost

http://www.petri.co.il/forums/showthread.php?t=348

'********************************************************************

'* Function IsPingable(strHost)

'*								

'*	Returns True or False based on the output from ping.exe	

'********************************************************************

Function IsPingable(strHost)

	Set objShell = WScript.CreateObject("WScript.Shell")

	Set objExecObject = objShell.Exec("cmd /c ping.exe -n 3 -w 1000 " &amp; strHost)

	Do While Not objExecObject.StdOut.AtEndOfStream

		strText = objExecObject.StdOut.ReadLine()

		If Instr(strText, "Reply") > 0 Then

	        		'Wscript.Echo "Reply received."

	        		IsPingable = True

			Exit Do

		End If

	Loop

	If (IsPingable &lt;> True) Then

		IsPingable = False

	End If

End Function

Open in new window

0
 
LVL 25

Expert Comment

by:Ron M
Comment Utility
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

This paper addresses the security of Sennheiser DECT Contact Center and Office (CC&O) headsets. It describes the DECT security chain comprised of “Pairing”, “Per Call Authentication” and “Encryption”, which are all part of the standard DECT protocol.
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now