Page 1 of 2 12 LastLast
Results 1 to 10 of 14

Thread: Forced shutdown of a remote nt/2k server

  1. #1
    Senior Member
    Join Date
    Apr 2002
    Posts
    324

    Lightbulb Forced shutdown of a remote nt/2k server

    When restarting a remote NT based server from the gui, NT stops any remote administration service (eg WinVNC/PC-Anywhere/BO etc) that you have running. If the machine fails to reboot cleanly (say a dialog box appears during shutdown) and your remote administration service has stopped you are fuxored. I work from home most of the time and so I object to having to get dressed to go and see sick servers .

    To get around this problem I wanted to write a program to implicitly force a reboot from the command line. By 'force a reboot' I mean telling the system to shut down ignoring any dialog boxes, errors, tasks waiting to complete or other anomalies, and restart regardless. This was intended to be an application of last resort, but I have had it implemented on my own servers for a couple of months now and it has been so successful that I made it policy to do all server reboots using this command line app - rather than attempting a shutdown via the gui first.

    Notes on the code

    This program uses the windows APIs. Because of this you could write it in any number of languages, but the example below is given in Visual Basic. Also I can't take 100% credit for the code - A lot of the API stuff is cut and pasted from API reference sites such as www.vbapi.com, but I have stitched it all together, added comments and the command line interface.

    If you're going to try to get this code working in VB you'll have to create a new project containing just one .bas module and add a reference to "Visual Basic for Applications". This is for the retrieval of command line parameters. Then copy and paste the code listed below into your module.

    Retrieving the O/S type

    This code is only meant to run on versions of WinNT. So first of all we have to have a little bit of sanity checking. Is this a WinNT box? We can use the GetVersionEx API to get the version of our target operating system. The IsWinNT() function populates the myos value (of OSVERSIONINFO type) with information about the target operating system. If the target system is an NT box the following statement (and therefore the IsWinNT() function) will return true:
    Code:
    Private Const VER_PLATFORM_WIN32_NT = 2
    ...
    IsWinNT = (myOS.dwPlatformId = VER_PLATFORM_WIN32_NT)
    Setting shutdown privileges for the current thread

    Ok. Now we know that the target system is NT we need to set the priveledges on our application so that we can shut down the system. To do this we use the GetCurrentProcess, LookupPrivilegeValue and AdjustTokenPrivileges APIs. The EnableShutDown subroutine uses the GetCurrentProcess API to get the handle for the current process and assign that process with permission to shutdown the system. I won't go into this too much here because I document this rather heavily in the code.

    Retreiving user input from the command line

    Sub main splits command line parameters, which are stored in the command$ variable, into an array using space as the deliminator. The code checks for two parameters, the action (valid options are logoff/reboot/shutdown prefaced by either - or /) and a boolean force variable (similarly prefaced) that decides whether or not to force the selected action. This bit of the code requires a reference to Visual Basic for Application so as to access the script host.

    Forcing a reboot

    The ShutDownNT procedure accepts the Flags parameter that specifies the action to be taken. The actual action taken by the ExitWindowsEx API contained in the ShutDownNT procedure is defined by assigning the sum of the following constants to the passed Flags variable:
    Code:
    Private Const EWX_LOGOFF = 0
    Private Const EWX_SHUTDOWN = 1
    Private Const EWX_REBOOT = 2
    Private Const EWX_FORCE = 4
    So for example the flags required for a forced reboot would be:
    Code:
    Private Const EWX_LOGOFF = 0
    Private Const EWX_SHUTDOWN = 1
    Private Const EWX_REBOOT = 2
    Private Const EWX_FORCE = 4
    ...
    flags = (EWX_FORCE + EWX_REBOOT)
    'or flags = 4 + 2
    The code!

    Code:
    Option Explicit
    
    Private Const action_REBOOT = 1
    Private Const action_LOGOFF = 2
    Private Const action_SHUTDOWN = 3
    
    'API constants
    Private Const EWX_LOGOFF = 0
    Private Const EWX_SHUTDOWN = 1
    Private Const EWX_REBOOT = 2
    Private Const EWX_FORCE = 4
    Private Const TOKEN_ADJUST_PRIVILEGES = &H20
    Private Const TOKEN_QUERY = &H8
    Private Const SE_PRIVILEGE_ENABLED = &H2
    Private Const ANYSIZE_ARRAY = 1
    Private Const VER_PLATFORM_WIN32_NT = 2
    
    'API structures
    Public Type OSVERSIONINFO
        dwOSVersionInfoSize As Long
        dwMajorVersion As Long
        dwMinorVersion As Long
        dwBuildNumber As Long
        dwPlatformId As Long
        szCSDVersion As String * 128
    End Type
    
    Public Type LUID
        LowPart As Long
        HighPart As Long
    End Type
    
    Public Type LUID_AND_ATTRIBUTES
        pLuid As LUID
        Attributes As Long
    End Type
    
    Public Type TOKEN_PRIVILEGES
        PrivilegeCount As Long
        Privileges(ANYSIZE_ARRAY) As LUID_AND_ATTRIBUTES
    End Type
    
    'API Declarations
    Private Declare Function GetCurrentProcess Lib "kernel32.dll" () As Long
    
    Private Declare Function OpenProcessToken Lib "advapi32.dll" _
    (ByVal ProcessHandle As Long, ByVal DesiredAccess As Long, _
    TokenHandle As Long) As Long
    
    Private Declare Function LookupPrivilegeValue Lib "advapi32.dll" _
    Alias "LookupPrivilegeValueA" (ByVal lpSystemName As String, _
    ByVal lpName As String, lpLuid As LUID) As Long
    
    Private Declare Function AdjustTokenPrivileges Lib "advapi32.dll" _
    (ByVal TokenHandle As Long, ByVal DisableAllPrivileges As Long, _
    NewState As TOKEN_PRIVILEGES, ByVal BufferLength As Long, _
    PreviousState As TOKEN_PRIVILEGES, ReturnLength As Long) As Long
    Private Declare Function ExitWindowsEx Lib "user32.dll" _
    (ByVal uFlags As Long, ByVal dwReserved As Long) As Long
    
    Private Declare Function GetVersionEx Lib "kernel32.dll" _
    Alias "GetVersionExA" (ByRef lpVersionInformation As OSVERSIONINFO) As Long
    
    
    Sub Main()
       Dim a_strArgs() As String
       Dim i As Integer
       Dim Force As Boolean
       Dim Action As Integer
       Dim Flags as Long
       
       'Sanity checking to see if the target system is NT
       If IsWinNT = True Then
        'Reset system variables
        Force = False
        Action = 0
    
        'Split the contents of the command$ variable into the a_strArgs array
        'using [space] as the deliminator.
        a_strArgs = Split(Command$, " ")
        'Iterate throught the a_strArgs array
        For i = LBound(a_strArgs) To UBound(a_strArgs)
           Select Case LCase(a_strArgs(i))
           Case "-logoff", "/logoff"
            Action = action_LOGOFF
           Case "-reboot", "/reboot"
            Action = action_REBOOT
           Case "-shutdown", "/shutdown"
            Action = action_SHUTDOWN
           Case "-force", "/force", "/f", "-f"
              Force = True
           Case Else
              Exit Sub
           End Select
         Next i
      End If
        
        'If an action has been set then enable the shutdown priveledges
        'on this process
        If Action > 0 Then
          EnableShutDown
        Else
          'No action has been selected so terminate
          Exit Sub
        End If
        
        'Calculate the sum of the required flags and pass this as a 
        'parameter to the ShutDownNT procedure.
        if force = true then flags = EWX_FORCE
        Select Case Action
          Case action_LOGOFF
            flags = flags + EWX_LOGOFF
    	ShutDownNT(flags)
          Case action_REBOOT
    	flags = flags + EWX_LOGOFF
            ShutDownNT(flags)
          Case action_SHUTDOWN
    	flags = flags + EWX_LOGOFF
            ShutDownNT(flags)
        End Select
    
    End Sub
    
    Public Function IsWinNT() As Boolean
        Dim myOS As OSVERSIONINFO
    
        'I think I pretty much covered this above
        myOS.dwOSVersionInfoSize = Len(myOS)
        GetVersionEx myOS
        IsWinNT = (myOS.dwPlatformId = VER_PLATFORM_WIN32_NT)
    End Function
    
    'set the shut down privilege for the current application
    Private Sub EnableShutDown()
        Dim hProc As Long
        Dim hToken As Long
        Dim mLUID As LUID
        Dim mPriv As TOKEN_PRIVILEGES
        Dim mNewPriv As TOKEN_PRIVILEGES
    
        'Get the process ID of the this process 
        'and place it in the hproc variable
        hProc = GetCurrentProcess()
    
        'Open the hProc process and lookup the 
        'SeShutdownPrivilege value
        OpenProcessToken hProc, TOKEN_ADJUST_PRIVILEGES + TOKEN_QUERY, hToken
        LookupPrivilegeValue "", "SeShutdownPrivilege", mLUID
        
        'Create a  new set of priveledges in the mPriv variable
        'of token priveledges type
        mPriv.PrivilegeCount = 1
        mPriv.Privileges(0).Attributes = SE_PRIVILEGE_ENABLED
        mPriv.Privileges(0).pLuid = mLUID
        
        ' enable shutdown privilege for the current application
        AdjustTokenPrivileges hToken, False, mPriv, _
        4 + (12 * mPriv.PrivilegeCount), mNewPriv, _
        4 + (12 * mNewPriv.PrivilegeCount)
    End Sub
    
    ' Shut Down NT
    Public Sub ShutDownNT(Flags as Long)
        ExitWindowsEx Flags, 0
    End Sub
    If you want to get a copy of this app without the bother of compiling it yourself you can download a zipped copy from my public FTP server at ftp://195.8.181.206/SimonSoft/shutdown.zip

    Whilst every care is taken to ensure that files on this FTP are virus and error free you are advised to scan any files you download. Usage is entirely at your own risk. If you use any other software from this server and intent to keep it please support it's creators by buying a valid licence.

    If you enjoyed this tutorial have a look at these:
    Scripting Internet Connections Under Window$
    Securing an installation of IIS 4. (No, seriously)
    Remote DSN Connections, using WinAPIs and the registry
    \"I may not agree with what you say, but I will defend to the death your right to say it.\"
    Sir Winston Churchill.

  2. #2
    Antionline Quitter..Srsly
    Join Date
    Aug 2001
    Posts
    457
    impresive bit of coding....personally i am not creative to even think of some of the stuff u did with VB ....i personally dont need it but i was wondering how would u have ot tweak it for win2k serv or adv serv?...i am sure some ppl might need it...now adays win nt isnt used as much and maybe u should recode it for 2k
    \"\"A weak mind is like a microscope, which magnifies trifling things but cannot receive great ones.\" — G.K. Chesterton, 19th-century English essayist and poet\"

  3. #3
    Senior Member
    Join Date
    Apr 2002
    Posts
    324
    emrys --

    This works with /all/ flavours of NT. That includes 2k, which is in actual fact NT 5. I don't use XP as yet - never 'buy' (and I use the term loosley here to encompass any transaction you walk away from with a new piece of software ) anything from M$ until /at least/ service pack 3 unless you really want to be a beta tester - but if XP uses the NT kernel (and I don't see why it wouldn't - if it ain't broke you don't fix it) it should work on XP aswell.
    \"I may not agree with what you say, but I will defend to the death your right to say it.\"
    Sir Winston Churchill.

  4. #4
    Senior Member
    Join Date
    Sep 2001
    Posts
    1,027
    The w2k resource kit has a utility called shutdown.exe that should does pretty much the same as your code (I think )

    Ammo
    Credit travels up, blame travels down -- The Boss

  5. #5
    Senior Member
    Join Date
    Apr 2002
    Posts
    324
    Yeah - but mine's open source
    \"I may not agree with what you say, but I will defend to the death your right to say it.\"
    Sir Winston Churchill.

  6. #6
    Senior Member
    Join Date
    Apr 2002
    Posts
    324
    Ok - apologies if my last post was a bit flippant - it's getting late. Upon refelection what I probably meant was: IMHO the code is worthwhile just for the sake of the code. There are some bits that would be useful for any number of apps so I figured it was worth posting.
    \"I may not agree with what you say, but I will defend to the death your right to say it.\"
    Sir Winston Churchill.

  7. #7
    Antionline Quitter..Srsly
    Join Date
    Aug 2001
    Posts
    457
    NTSA : cool....well i have XP so i might try it just for the hell of it ...not that i use remote desktop but oh well :/
    \"\"A weak mind is like a microscope, which magnifies trifling things but cannot receive great ones.\" — G.K. Chesterton, 19th-century English essayist and poet\"

  8. #8
    Senior Member
    Join Date
    Sep 2001
    Posts
    1,027
    ntsa: yeah I understand, just wanted to mention it to others looking for that kind of tool... (if the didn't want to build your code for some reason )

    Ammo
    Credit travels up, blame travels down -- The Boss

  9. #9
    Senior Member
    Join Date
    Apr 2002
    Posts
    324
    If you download the zipped exe and try it on XP let me know what results you have. I'd be interested. TIA.
    \"I may not agree with what you say, but I will defend to the death your right to say it.\"
    Sir Winston Churchill.

  10. #10
    Senior Member
    Join Date
    Oct 2001
    Posts
    748
    "shutdown /c /l /r /y" will do what you wanted(closes all programs, answers yes to any popups, and reboots the server).

    Just confirming the earlier post about shutdown. Also, how does your system shutdown get logged on Win2K machines? IE., does the shutdown event in the system log show up as expected or unexpected? I have seen some instances where using shutdown from the Win toolkit causes the system to think the system shutdown was unexpected. This is not really a big issue as long as you know what to expect though.

    There is also a command called "logoff" in Win2k. Comes in handy when using terminal server.

    You can get a list of all users with open sessions on a machine by doing "query session." Then using the session ID provided from that you can "logoff X" where x is the session ID. Just throwing this in because I saw you had some variables for a logoff function.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •