?
Solved

Script to restart servers

Posted on 2007-08-11
9
Medium Priority
?
4,204 Views
Last Modified: 2013-11-05
I'm looking for a script that will run from a central computer that restarts servers in a specific order and when the previous server is back up.

Example:
1. restart server1
2. ping server1 until reply
3. restart server2
4. ping server2 until reply
5. restart server3
6. ping server3 until reply
7. if error, send email notification and write to log
8. when finished close script

I was thinking something in either vbscript or as a bat file that I can either manually run or schedule as a task.  


0
Comment
Question by:drunkennoodle
9 Comments
 
LVL 19

Expert Comment

by:weellio
ID: 19677534
i haven't added the email portion as there are so many ways to set this up,
do you want to use outlook? cdo? smtp? yadda yadda,. what OS will the script be run from?

here is something i just threw together havent testedit yet, let me know if this works for you

'**********************************************************************************************
strwritefile = "C:\results.txt" ' results text file you can change the locatin and name here

'create an array for the computers
dim arycomp(2)
arycomp(0) = "server1"
arycomp(1) = "server2"
arycomp(2) = "server3"

Set fso = CreateObject("Scripting.FileSystemObject")
Set rFile = fso.CreateTextFile(strwritefile, True)


'reboot the first box
'assumes that you can already connect to server1
rebootme(arycomp(0))

for i=0 to 2
Set objShell = CreateObject("WScript.Shell")
Set objExec = objShell.Exec("ping -n 2 -w 1000 " & arycomp(i))
strPingResults = LCase(objExec.StdOut.ReadAll)
response = "no"
'wait until ping results  is yes
do until response = "yes"
      If InStr(strPingResults, "reply from") Then
            rFile.writeline now & vbtab & arycomp(i) & ": responded to ping."
            response = "yes"
      Else
            WScript.Echo strTarget & " did not respond to ping."
      End If
loop
'once ping results = yes, then reboot the next box
'if the last box has already run, then do nothing
if not arycomp(i + 1) = "" then
            rebootme(arycomp(i + 1))
end if
next

rFile.writeline now & vbtab & "Process Ended"
rFile.close
wscript.echo "Results saved to " & strwritefile


Function rebootme(box)
'function to reboot the computers using wmi
on error resume next
        Set OpSysSet =  GetObject("winmgmts:{impersonationLevel=impersonate,(RemoteShutdown)}//" &_
                                    box).ExecQuery("select * from Win32_OperatingSystem where Primary=true")
            If Err.number <> 0 Then
                  errlog("Problem connecting to " & box)
            else
            end if
        for each OpSys in OpSysSet
            rFile.writeline now & vbtab & box & ": Rebooted"
            OpSys.Reboot()
        next
on error goto 0      
wscript.sleep(15000) 'sleep for 15 seconds to make sure the computer has sufficient time to connect and shutdown
end function

sub errlog(errmsg)
rFile.writeline now & vbtab & errmsg
rFile.writeline now & vbtab & Err.Description & " : " & Err.Number
' Clear error
      Err.Clear  
' Reset error handling
      On Error Goto 0
end sub
0
 
LVL 51

Expert Comment

by:ahoffmann
ID: 19682090
> 2. ping server1 until reply
and if it never replies?
0
 

Author Comment

by:drunkennoodle
ID: 19683329
@ ahoffmann
See step 7.

7. if error, send email notification and write to log

If it never replies then I need an email notification and write to a log that the server never came back up from restart.
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 

Author Comment

by:drunkennoodle
ID: 19683352
@ weellio
I'm either going to run this from Windows XP, Vista, or Server 2003.  At this moment it is Windows XP

I would like the email to be sent via smtp.
0
 
LVL 19

Accepted Solution

by:
weellio earned 2000 total points
ID: 19684881
gotta be picky,.., try this out



strwritefile = "C:\results.txt" ' results text file you can change the location and name here
strsmtp_server = "smtpserver"  ' your smtp servername
strmailto = "x@yzcompany.com"            ' your email address comma delimited for multiple addresses
strmailfrom = "Serverrebooter@somewhere.com" ' from email address can be anything
strsubject = "Reboot Script"
strbody = "This is the first line in the message body" & vbcrlf 'if you want a specific message everytime

'create an array for the computers
dim arycomp(2)
arycomp(0) = "server1"
arycomp(1) = "server2"
arycomp(2) = "server3"

Set fso = CreateObject("Scripting.FileSystemObject")
Set rFile = fso.CreateTextFile(strwritefile, True)


'reboot the first box
'assumes that you can already connect to server1
rebootme(arycomp(0))

for i=0 to 2
Set objShell = CreateObject("WScript.Shell")
Set objExec = objShell.Exec("ping -n 2 -w 1000 " & arycomp(i))
strPingResults = LCase(objExec.StdOut.ReadAll)
response = "no"
'wait until ping results  is yes
wait = 1
do until response = "yes"
    if wait < 90 Then 'after 15 minutes quit script
            if wait <> 30 then ' if not responded within 5 minutes, then send email.  
              If InStr(strPingResults, "reply from") Then
                        rFile.writeline now & vbtab & arycomp(i) & ": responded to ping."
                        strbody = strbody & now & vbtab & arycomp(i) & ": responded to ping." & vbcrlf
                        response = "yes"
                        wait = 1
              Else
                        strbody = strbody & now & vbtab &  arycomp(i)  & " did not respond to ping." & vbcrlf
                        WScript.Echo arycomp(i)  & " did not respond to ping."
              End If
            else
                  strbody = strbody & now & vbtab & arycomp(i) & "Not responding to Ping" & vbcrlf
                  mailme strmailto, strsubject, strbody, strmailfrom, strsmtp_server
            end If
      else
            strbody = strbody & now & vbtab & arycomp(i) & "Waited 15 minutes for response. Script Quitting" & vbcrlf
            mailme strmailto, strsubject, strbody, strmailfrom, strsmtp_server
            wscript.quit (1)
      end if
wscript.sleep(10000) 'wait ten seconds between each ping
wait = wait + 1
Loop

'once ping results = yes, then reboot the next box
'if the last box has already run, then do nothing
if not arycomp(i + 1) = "" then
            rebootme(arycomp(i + 1))
end if
next

rFile.writeline now & vbtab & "Process Ended"
rFile.close
wscript.echo "Results saved to " & strwritefile
mailme strmailto, strsubject, strbody, strmailfrom, strsmtp_server


Function rebootme(box)
'function to reboot the computers using wmi
on error resume next
        Set OpSysSet =  GetObject("winmgmts:{impersonationLevel=impersonate,(RemoteShutdown)}//" &_
                                    box).ExecQuery("select * from Win32_OperatingSystem where Primary=true")
            If Err.number <> 0 Then
                  errlog("Problem connecting to " & box)
            Else
            End if
        for Each OpSys in OpSysSet
            rFile.writeline now & vbtab & box & ": Rebooted"
                  strbody = strbody & now & vbtab & box & ": Rebooted" & vbcrlf
            OpSys.Reboot()
        Next
on error GoTo 0      
wscript.sleep(15000) 'sleep for 15 seconds to make sure the computer has sufficient time to connect and shutdown
end Function

sub errlog(errmsg)
rFile.writeline now & vbtab & errmsg
rFile.writeline now & vbtab & Err.Description & " : " & Err.Number
' Clear Error
      Err.Clear  
' Reset error handling
      On Error Goto 0
end Sub

Sub mailme(aTo, Subject, TextBody, aFrom, strsmtp)
 ' Static Conf As New CDO.Configuration
  If IsEmpty(Conf) Then
    Const cdoSendUsingPort = 2
    Set Conf = CreateObject("CDO.Configuration")
    With Conf.Fields
      .Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = _
                    cdoSendUsingPort
      .Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = _
                    strsmtp
      .Update
    End With
  End If
 
  Dim Message 'As New CDO.Message
 
  'Create CDO message object
  Set Message = CreateObject("CDO.Message")
  With Message
    'Set cached configuration
    Set .Configuration = Conf
   
    'Set email adress, subject And body
    .To = aTo
    .Subject = Subject
    .TextBody = TextBody
   
    'Set sender address If specified.
    If Len(aFrom) > 0 Then .From = aFrom
   
    'Send the message
    .Send
  End With
End Sub


'cached configuration
0
 

Author Comment

by:drunkennoodle
ID: 19729957
Thanks weellio.  I haven't had a chance to test your script but you have provided a foundation script for me to use.
0
 
LVL 19

Expert Comment

by:weellio
ID: 19735328
well if you don't try it soon, im' sure i will,. i have a series of servers that need to be rebooted in order.. if i make any modifications to it i'll post them here.
0
 

Expert Comment

by:Lana85
ID: 25533524
Hi weelio

I'm looking for a script that could restart serveurs listed in excel sheet at different schedul time and different group.

For exemple: in my sheet xls file
SERVER NAME        |         SCHEDULE TIME        |            REBOOT           |           GROUP
Server 1                           3:00 pm - 5:00 pm                     yes                        week-end 1(1srt of month)
Server 2                           4:00 pm - 6:00 pm                     not                         week-end 2 (2nd of month)
Server 3                           4:00 pm - 6:00 pm                     yes                        week-end 2 (2nd of month)
..
..
Server x                           4:00 pm - 6:00 pm                     yes                        week-end 3 (2nd of month)

I've started to tweak it but I can't add some code for value time and group time. Do you think you' could help me please?

Const adVarChar = 200
Const MaxCharacters = 255
Const adDate = 7
Const ForWriting = 1
 
Dim strWriteFile = "c:\Logs\"
 
Set objDRS = CreateObject("ADOR.Recordset")
 objDRS.Fields.Append "Server" , adVarChar , MaxCharacters
 objDRS.Fields.Append "Time" , adDate
 objDRS.Fields.Append "Reboot" , adVarChar , MaxCharacters
objDRS.Open
 
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = False
Set objWorkBook = objExcel.WorkBooks.Open("C:\Reboot.xls")
Set objWorkSheet = objWorkBook.Sheets("Sheet1")
 
intRow = 2
 
Do Until objExcel.Cells(intRow, 1).Value = ""
    objDRS.AddNEW
    objDRS("Server").Value =  objExcel.Cells(intRow, 1).Value
    objDRS("Time").Value = objExcel.Cells(intRow, 2).Value
    objDRS("Reboot").Value = objExcel.Cells(intRow, 3).Value
   intRow = intRow + 1
Loop
 
objExcel.Quit
 
objDRS.Sort = "Reboot DESC" ' Use DESC/ASC to specify sort order.
objDRS.MoveFirst
 
dim arycomp()
intSize = 0
 
Do Until objDRS.EOF
  If objDRS.Fields.Item("Reboot") = "Yes" Then
   ReDim Preserve arycomp(intSize)
    arycomp(intSize) = objDRS.Fields.Item("Server")
    intSize = intSize + 1
  Else
  End If
  objDRS.MoveNext
Loop
 
Set objobjFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objobjFSO.CreateTextFile(strWriteFile, ForWriting)
 
for i=0 to 2
 Set objShell = CreateObject("WScript.Shell")
 Set objExec = objShell.Exec("ping -n 2 -w 1000 " & arycomp(i))
 strPingResults = LCase(objExec.StdOut.ReadAll)
 response = "no"
 'wait until ping results  is yes
 wait = 1
 do until response = "yes"
     if wait < 90 Then 'after 15 minutes quit script
             if wait <> 30 then ' if not responded within 5 minutes, then send email. 
               If InStr(strPingResults, "reply from") Then
                        objFILE.WriteLine now & vbtab & arycomp(i) & ": responded to ping."
                         strbody = strbody & now & vbtab & arycomp(i) & ": responded to ping." & vbcrlf
                         response = "yes"
                         wait = 1
               Else
                         strbody = strbody & now & vbtab &  arycomp(i)  & " did not respond to ping." & vbcrlf
                         WScript.Echo arycomp(i)  & " did not respond to ping."
               End If
             else
                   strbody = strbody & now & vbtab & arycomp(i) & "Not responding to Ping" & vbcrlf
             end If
       else
             strbody = strbody & now & vbtab & arycomp(i) & "Waited 15 minutes for response. Script Quitting" & vbcrlf
             wscript.quit (1)
       end if
 wscript.sleep(10000) 'wait ten seconds between each ping
 wait = wait + 1
 Loop
 
 'once ping results = yes, then reboot the next box
 'if the last box has already run, then do nothing
 if not arycomp(i + 1) = "" then
             RebootMe(arycomp(i + 1))
 end if
 next
 
objFILE.WriteLine now & vbtab & "Process Ended"
objFILE.close
 wscript.echo "Results saved to " & strWriteFile
 
 Function RebootMe(box)
 'function to reboot the computers using wmi
 on error resume next
         Set OpSysSet =  GetObject("winmgmts:{impersonationLevel=impersonate,(RemoteShutdown)}//" &_
                                     box).ExecQuery("select * from Win32_OperatingSystem where Primary=true")
             If Err.number <> 0 Then
                   errlog("Problem connecting to " & box)
             Else
             End if
         for Each OpSys in OpSysSet
            objFILE.WriteLine now & vbtab & box & ": Rebooted"
                   strbody = strbody & now & vbtab & box & ": Rebooted" & vbcrlf
             OpSys.Reboot()
         Next
 on error GoTo 0     
 wscript.sleep(15000) 'sleep for 15 seconds to make sure the computer has sufficient time to connect and shutdown
 end Function
 
 sub errlog(errmsg)
objFILE.WriteLine now & vbtab & errmsg
objFILE.WriteLine now & vbtab & Err.Description & " : " & Err.Number
 ' Clear Error
       Err.Clear 
 ' Reset error handling
       On Error Goto 0
 end Sub

Open in new window

0
 

Expert Comment

by:deloitteioc
ID: 34503594
Hi, When I try to use the above script to reboot server in order I can see the ping results have not returned for one server, yet the other start the reboot. Thanks
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Background Information Recently I have fixed file server permission issues for one of my client. The client has 1800 users and one Windows Server 2008 R2 domain joined file server with 12 TB of data, 250+ shared folders and the folder structure i…
A quick Powershell script I wrote to find old program installations and check versions of a specific file across the network.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
Suggested Courses
Course of the Month15 days, 6 hours left to enroll

839 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