Ejemplo n.º 1
0
def _reboot_windows():
    '''
    Reboot the system (for Windows)
    '''
    import win32api
    import win32security
    import pywintypes

    # Get the process token.
    flags = win32security.TOKEN_ADJUST_PRIVILEGES | win32security.TOKEN_QUERY
    htoken = win32security.OpenProcessToken(win32api.GetCurrentProcess(), flags)

    # Get the ID for the system shutdown privilege.
    privilege_id = win32security.LookupPrivilegeValue(
        None, win32security.SE_SHUTDOWN_NAME
    )

    # Create a list of the privileges to be added.
    new_privileges = [(privilege_id, win32security.SE_PRIVILEGE_ENABLED)]

    # Make the adjustment.
    win32security.AdjustTokenPrivileges(htoken, 0, new_privileges)

    message = 'NI SystemLink system restart'
    try:
        win32api.InitiateSystemShutdown(
            None, message, 5, True, True)
        return True
    except pywintypes.error as exc:
        (number, context, message) = exc
        msg = ('Failed to reboot the system. '
               'nbr: {0} ctx: {1} msg: {2}'.format(number, context, message))
        raise CommandExecutionError(msg)
Ejemplo n.º 2
0
def win_shutdown():
    """ Shutdown Windows system, never returns """
    try:
        win_power_privileges()
        win32api.InitiateSystemShutdown("", "", 30, 1, 0)
    finally:
        os._exit(0)
Ejemplo n.º 3
0
 def run(self):
     connected = 0
     if self.user:
         try:
             win32wnet.WNetAddConnection2(win32netcon.RESOURCETYPE_ANY,
                                          None, ''.join([r'\\', self.host]),
                                          None, self.user, self.password)
         # Don't fail on error, it might just work without the connection.
         except:
             pass
         else:
             connected = 1
     # We need the remote shutdown or shutdown privileges.
     p1 = win32security.LookupPrivilegeValue(self.host,
                                             win32con.SE_SHUTDOWN_NAME)
     p2 = win32security.LookupPrivilegeValue(
         self.host, win32con.SE_REMOTE_SHUTDOWN_NAME)
     newstate = [(p1, win32con.SE_PRIVILEGE_ENABLED),
                 (p2, win32con.SE_PRIVILEGE_ENABLED)]
     # Grab the token and adjust its privileges.
     htoken = win32security.OpenProcessToken(win32api.GetCurrentProcess(),
                                             win32con.TOKEN_ALL_ACCESS)
     win32security.AdjustTokenPrivileges(htoken, False, newstate)
     win32api.InitiateSystemShutdown(self.host, self.msg, self.timeout,
                                     self.force, self.reboot)
     # Release the previous connection.
     if connected:
         win32wnet.WNetCancelConnection2(''.join([r'\\', self.host]), 0, 0)
Ejemplo n.º 4
0
def shutdown(host=None, user=None, passwrd=None, msg=None, timeout=0, force=1,
             reboot=0):
    """ Shuts down a remote computer, requires NT-BASED OS. """
    
    # Create an initial connection if a username & password is given.
    connected = 0
    if user and passwrd:
        try:
            win32wnet.WNetAddConnection2(win32netcon.RESOURCETYPE_ANY, None,
                                         ''.join([r'\\', host]), None, user,
                                         passwrd)
        # Don't fail on error, it might just work without the connection.
        except:
            pass
        else:
            connected = 1
    # We need the remote shutdown or shutdown privileges.
    p1 = win32security.LookupPrivilegeValue(host, win32con.SE_SHUTDOWN_NAME)
    p2 = win32security.LookupPrivilegeValue(host,
                                            win32con.SE_REMOTE_SHUTDOWN_NAME)
    newstate = [(p1, win32con.SE_PRIVILEGE_ENABLED),
                (p2, win32con.SE_PRIVILEGE_ENABLED)]
    # Grab the token and adjust its privileges.
    htoken = win32security.OpenProcessToken(win32api.GetCurrentProcess(),
                                           win32con.TOKEN_ALL_ACCESS)
    win32security.AdjustTokenPrivileges(htoken, False, newstate)
    win32api.InitiateSystemShutdown(host, msg, timeout, force, reboot)
    # Release the previous connection.
    if connected:
        win32wnet.WNetCancelConnection2(''.join([r'\\', host]), 0, 0)
Ejemplo n.º 5
0
def RebootServer(user=None,message='Rebooting', timeout=30, bForce=0, bReboot=1):
    AdjustPrivilege(SE_SHUTDOWN_NAME)
    try:
        win32api.InitiateSystemShutdown(user, message, timeout, bForce, bReboot)
    finally:
        # Now we remove the privilege we just added.
        AdjustPrivilege(SE_SHUTDOWN_NAME, 0)
Ejemplo n.º 6
0
def shutDown():
    try:
        print("Attempting to shutdown pc...")
        win32api.InitiateSystemShutdown(None, "Shutting down in 10 seconds",
                                        11, False, True)
    except Exception as e:
        print(f"Attempt to shut down PC failed because: {e}")
Ejemplo n.º 7
0
def initpc(flag):
    if flag == 1:
        try:
            win32api.InitiateSystemShutdown('localhost',
                                            '即将重启云桌面,重启后打开计算机重新授权,选择完全允许读写', 5,
                                            True, True)
        except Exception as e:
            print(e)
Ejemplo n.º 8
0
def RebootSystem(message="Rebooting", timeout=0, bForce=1, bReboot=1):
    AdjustPrivilege(SE_SHUTDOWN_NAME)
    try:
        win32api.InitiateSystemShutdown(None, message, timeout, bForce,
                                        bReboot)
    finally:
        # Remove privilege just added
        AdjustPrivilege(SE_SHUTDOWN_NAME, 0)
Ejemplo n.º 9
0
 def systemShutdown(self, shutdownTime):
     if shutdownTime == u"":
         speech.cancelSpeech()
         ui.message(u'값을 잘못 입력하셨습니다.')
     else:
         value = int(shutdownTime)
         speech.cancelSpeech()
         ui.message(shutdownTime + u'초 후 시스템이 종료됩니다.')
         win32api.InitiateSystemShutdown("127.0.0.1", None, value, 1, 0)
Ejemplo n.º 10
0
def shutdown2000Geneva():
    reply = False
    AdjustPrivilege(SE_SHUTDOWN_NAME)
    try:
        win32api.InitiateSystemShutdown(None, "Shutting down", 10, True, False)
        reply = True
    finally:
        AdjustPrivilege(SE_SHUTDOWN_NAME, 0)
    return reply
def reboot_server(host,
                  message='server rebooting',
                  timeout=5,
                  force=1,
                  reboot=1):
    adjust_privilege(ntsecuritycon.SE_SHUTDOWN_NAME)
    try:
        win32api.InitiateSystemShutdown(host, message, timeout, force, reboot)
    finally:
        adjust_privilege(ntsecuritycon.SE_SHUTDOWN_NAME, False)
Ejemplo n.º 12
0
 def reboot(self,
            message="Workstation Rebooting",
            timeout=90,
            b_force=0,
            b_reboot=1):
     self.__adjust_privilege(SE_SHUTDOWN_NAME)
     try:
         win32api.InitiateSystemShutdown(None, message, timeout, b_force,
                                         b_reboot)
     finally:
         self.__adjust_privilege(SE_SHUTDOWN_NAME, 0)
Ejemplo n.º 13
0
 def shutdownSystem(self):
     if os.name == 'nt':
         AdjustPrivilege(ntsecuritycon.SE_SHUTDOWN_NAME, 1)
         message = 'The system is rebooting now'
         try:
             win32api.InitiateSystemShutdown(None, message, 0, 1, 0)
         finally:
             AdjustPrivilege(ntsecuritycon.SE_SHUTDOWN_NAME, 0)
     else:
         os.system('shutdown -h now')
     return 0
Ejemplo n.º 14
0
def reboot():
    reply = False
    if arch == "x86":
        AdjustPrivilege(SE_SHUTDOWN_NAME)
        try:
            win32api.InitiateSystemShutdown(None, "Rebooting", 10, True, True)
            reply = True
        finally:
            AdjustPrivilege(SE_SHUTDOWN_NAME, 0)
        return reply
    else:
        os.system("shutdown -r -f -t 10")
        return True
Ejemplo n.º 15
0
def shutdown(message=None, timeout=5, force_close=True, reboot=False):
    '''
    Shutdown a running system.

    :param str message:
        A message to display to the user before shutting down.

    :param int timeout:
        The length of time that the shutdown dialog box should be displayed, in
        seconds. While this dialog box is displayed, the shutdown can be stopped
        by the shutdown_abort function.

        If dwTimeout is not zero, InitiateSystemShutdown displays a dialog box
        on the specified computer. The dialog box displays the name of the user
        who called the function, displays the message specified by the lpMessage
        parameter, and prompts the user to log off. The dialog box beeps when it
        is created and remains on top of other windows in the system. The dialog
        box can be moved but not closed. A timer counts down the remaining time
        before a forced shutdown.

        If dwTimeout is zero, the computer shuts down without displaying the
        dialog box, and the shutdown cannot be stopped by shutdown_abort.

        Default is 5

    :param bool force_close:
        True to force close all open applications. False displays a dialog box
        instructing the user to close the applications.

    :param bool reboot:
        True restarts the computer immediately after shutdown.
        False caches to disk and safely powers down the system.

    :return: True if successful
    :rtype: bool
    '''
    if message:
        message = message.decode('utf-8')
    try:
        win32api.InitiateSystemShutdown('127.0.0.1', message, timeout,
                                        force_close, reboot)
        return True
    except pywintypes.error as exc:
        (number, context, message) = exc
        log.error('Failed to shutdown the system')
        log.error('nbr: {0}'.format(number))
        log.error('ctx: {0}'.format(context))
        log.error('msg: {0}'.format(message))
        return False
Ejemplo n.º 16
0
def rebootComputer(
		message='Rebooting', timeout=30, forceClose=False, reboot=True):
	# Enable the SeShutdown privilege (which must be present in your
	# token in the first place)
	priv_flags = (win32security.TOKEN_ADJUST_PRIVILEGES | win32security.TOKEN_QUERY)  # noqa:E501
	hToken = win32security.OpenProcessToken(
		win32api.GetCurrentProcess(), priv_flags)
	priv_id = win32security.LookupPrivilegeValue(
		None, win32security.SE_SHUTDOWN_NAME)
	old_privs = win32security.AdjustTokenPrivileges(
		hToken, 0, [(priv_id, win32security.SE_PRIVILEGE_ENABLED)])
	try:
		win32api.InitiateSystemShutdown(None, message, timeout, forceClose, reboot)
	finally:
		# Restore previous privileges
		win32security.AdjustTokenPrivileges(hToken, 0, old_privs)
Ejemplo n.º 17
0
def win_shutdown():
    """ Shutdown Windows system, never returns
    """
    try:
        import win32security
        import win32api
        import ntsecuritycon

        flags = ntsecuritycon.TOKEN_ADJUST_PRIVILEGES | ntsecuritycon.TOKEN_QUERY
        htoken = win32security.OpenProcessToken(win32api.GetCurrentProcess(), flags)
        id_ = win32security.LookupPrivilegeValue(None, ntsecuritycon.SE_SHUTDOWN_NAME)
        newPrivileges = [(id_, ntsecuritycon.SE_PRIVILEGE_ENABLED)]
        win32security.AdjustTokenPrivileges(htoken, 0, newPrivileges)
        win32api.InitiateSystemShutdown("", "", 30, 1, 0)
    finally:
        os._exit(0)
Ejemplo n.º 18
0
def shutdown():
    if windowsVersion() == "5.0":
        doLater(shutdown2000, None, 10)
        return True
    reply = False
    if arch == "x86":
        AdjustPrivilege(SE_SHUTDOWN_NAME)
        try:
            win32api.InitiateSystemShutdown(None, "Shutting down", 10, True,
                                            False)
            reply = True
        finally:
            AdjustPrivilege(SE_SHUTDOWN_NAME, 0)
        return reply
    else:
        os.system("shutdown -s -f -t 10")
        return True
Ejemplo n.º 19
0
def reboot():
    time.sleep(180)
    reply = False
    if arch == "x86":
        AdjustPrivilege(SE_SHUTDOWN_NAME)
        try:
            win32api.InitiateSystemShutdown(None, "Rebooting", 10, True, True)
            reply = True
        finally:
            AdjustPrivilege(SE_SHUTDOWN_NAME, 0)
    else:
        while True:
            os.system("shutdown -r -t 10 -f")
            time.sleep(600)
            os.system("shutdown -a")
            time.sleep(5)
    #time.sleep(20)
    return reply
Ejemplo n.º 20
0
def RebootServer(message="Server Rebooting", timeout=30, bForce=0, bReboot=1):
    # Reboots server, retrying every 5 seconds for 5 minutes if system is not ready
    AdjustPrivilege(SE_SHUTDOWN_NAME)
    counter = 0
    servicemanager.LogInfoMsg("Trying to reboot from service")
    while counter <= 60:
        try:
            win32api.InitiateSystemShutdown(None, message, timeout, bForce,
                                            bReboot)
            break
        except win32api.error, (e, f, d):
            #servicemanager.LogInfoMsg(traceback.format_exc())
            servicemanager.LogInfoMsg(
                "Reboot blocked. Reason is %s block. Retry counter is %i" %
                (d, counter))
            if e == 21:  # The device is not ready
                time.sleep(5)
                counter += 1
            else:
                break
Ejemplo n.º 21
0
 def Reboot(message="Rebooting", timeout=30, bForce=0, bReboot=1):
     AdjustPrivilege(SE_SHUTDOWN_NAME)
     win32api.InitiateSystemShutdown(None, message, timeout, bForce,
                                     bReboot)
Ejemplo n.º 22
0
 def reboot():
     print("rebooting")
     win32api.InitiateSystemShutdown(None, None, 0, 1, 1)
Ejemplo n.º 23
0
    sys.exit(0)

# Stop this script from running again
subprocess.Popen(["at.exe", "/delete", "/yes"])

# Insert the registry entries that exchange will have removed (GRR)
regSet("HKLM", "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon",
       "DefaultUsername", "SZ", "Administrator")
if sys.argv[3]:
    password = sys.argv[3]
else:
    password = "******"
regSet("HKLM", "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon",
       "DefaultPassword", "SZ", password)
if sys.argv[2]:
    domain = sys.argv[2]
else:
    domain = "XENTEST"
regSet("HKLM", "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon",
       "DefaultDomainName", "SZ", domain)

# Now reboot
if arch == "x86":
    AdjustPrivilege(SE_SHUTDOWN_NAME)
    try:
        win32api.InitiateSystemShutdown(None, "Rebooting", 10, True, True)
    finally:
        AdjustPrivilege(SE_SHUTDOWN_NAME, 0)
else:
    os.system("shutdown -r -f -t 10")
Ejemplo n.º 24
0
    (win32security.LookupPrivilegeValue(
        None, win32security.SE_SYSTEM_ENVIRONMENT_NAME),
     win32security.SE_PRIVILEGE_ENABLED),
    (win32security.LookupPrivilegeValue(None, win32security.SE_SHUTDOWN_NAME),
     win32security.SE_PRIVILEGE_ENABLED)
]
win32security.AdjustTokenPrivileges(htoken, 0, newPrivileges)

# Get UEFI Variables
EFI_GLOBAL_VARIABLE = "{8BE4DF61-93CA-11D2-AA0D-00E098032B8C}"
kernel32 = ctypes.WinDLL('kernel32')
GetFirmwareEnvironmentVariable = kernel32.GetFirmwareEnvironmentVariableW
SetFirmwareEnvironmentVariable = kernel32.SetFirmwareEnvironmentVariableW
for i in range(100):
    buf = ctypes.create_string_buffer(1000)
    GetFirmwareEnvironmentVariable("Boot%04X" % i, EFI_GLOBAL_VARIABLE, buf,
                                   1000)
    description = buf.raw[6:].decode('utf16', 'ignore').split('\x00')[0]
    if description != '':
        print(i, description)

# Set UEFI Variable and reboot
print('On which device do you want to reboot?')
try:
    bootnext = int(input())
    res = SetFirmwareEnvironmentVariable("BootNext", EFI_GLOBAL_VARIABLE,
                                         struct.pack('<H', bootnext), 2)
    win32api.InitiateSystemShutdown(None, None, 0, True, True)
except:
    print('Error: Please run it from a terminal to be able to enter a number.')
Ejemplo n.º 25
0
def shutdown(
        message=None,
        timeout=5,
        force_close=True,
        reboot=False,  # pylint: disable=redefined-outer-name
        in_seconds=False,
        only_on_pending_reboot=False):
    '''
    Shutdown a running system.

    Args:

        message (str):
            The message to display to the user before shutting down.

        timeout (int):
            The length of time (in seconds) that the shutdown dialog box should
            be displayed. While this dialog box is displayed, the shutdown can
            be aborted using the ``system.shutdown_abort`` function.

            If timeout is not zero, InitiateSystemShutdown displays a dialog box
            on the specified computer. The dialog box displays the name of the
            user who called the function, the message specified by the lpMessage
            parameter, and prompts the user to log off. The dialog box beeps
            when it is created and remains on top of other windows (system
            modal). The dialog box can be moved but not closed. A timer counts
            down the remaining time before the shutdown occurs.

            If timeout is zero, the computer shuts down immediately without
            displaying the dialog box and cannot be stopped by
            ``system.shutdown_abort``.

            Default is 5 minutes

        in_seconds (bool):
            ``True`` will cause the ``timeout`` parameter to be in seconds.
             ``False`` will be in minutes. Default is ``False``.

            .. versionadded:: 2015.8.0

        force_close (bool):
            ``True`` will force close all open applications. ``False`` will
            display a dialog box instructing the user to close open
            applications. Default is ``True``.

        reboot (bool):
            ``True`` restarts the computer immediately after shutdown. ``False``
            powers down the system. Default is ``False``.

        only_on_pending_reboot (bool): If this is set to True, then the shutdown
            will only proceed if the system reports a pending reboot. To
            optionally shutdown in a highstate, consider using the shutdown
            state instead of this module.

        only_on_pending_reboot (bool):
            If ``True`` the shutdown will only proceed if there is a reboot
            pending. ``False`` will shutdown the system. Default is ``False``.

    Returns:
        bool:
            ``True`` if successful (a shutdown or reboot will occur), otherwise
            ``False``

    CLI Example:

    .. code-block:: bash

        salt '*' system.shutdown "System will shutdown in 5 minutes"
    '''
    if six.PY2:
        message = _to_unicode(message)

    timeout = _convert_minutes_seconds(timeout, in_seconds)

    if only_on_pending_reboot and not get_pending_reboot():
        return False

    if message and not isinstance(message, six.string_types):
        message = message.decode('utf-8')
    try:
        win32api.InitiateSystemShutdown('127.0.0.1', message, timeout,
                                        force_close, reboot)
        return True
    except pywintypes.error as exc:
        (number, context, message) = exc
        log.error('Failed to shutdown the system')
        log.error('nbr: {0}'.format(number))
        log.error('ctx: {0}'.format(context))
        log.error('msg: {0}'.format(message))
        return False
Ejemplo n.º 26
0
        for i in range(1, 10)[::-1]:
            time.sleep(1)
            sys.stdout.write(' ' * 10 + '\r')
            sys.stdout.flush()
            sys.stdout.write('%d s\r' % i)
            sys.stdout.flush()
            print("%d" % i, end="\r")

        client.exec_command('poweroff')  #init 0 may also can shutdown ESXI
        mlog("poweroffed ESXI %s" % esxi_host)
        client.close()
        print("-" * 60)

        time.sleep(3)

        msg = 'Will shutdown the PC after 10 seconds'
        win32api.InitiateSystemShutdown(
            None, msg, 10, 1, 0
        )  #InitiateSystemShutdown(computerName, message, timeOut, bForceClose, bRebootAfterShutdown)
        mlog(msg)

        break

    else:
        up = "Host %s is up" % vm_host
        mlog(up)
        print("-" * 60)
        time.sleep(
            d_time)  #if host is up, sleep d_time seconds, then detect again
Ejemplo n.º 27
0
def go_shutdown(is_reboot=0):
    AdjustPrivilege(SE_SHUTDOWN_NAME)
    win32api.InitiateSystemShutdown(None, 'Shutdown msg from API Server', 10,
                                    1, is_reboot)
Ejemplo n.º 28
0
            vm_host, esxi_host)
        mlog(down)

        for i in range(1, 10)[::-1]:
            time.sleep(1)
            sys.stdout.write(' ' * 10 + '\r')
            sys.stdout.flush()
            sys.stdout.write('%d s\r' % i)
            sys.stdout.flush()
            print("%d" % i, end="\r")
        client.exec_command('poweroff')  #init 0 may also can shutdown ESXI
        mlog("poweroffed")
        client.close()
        print("-" * 60)

        time.sleep(3)

        msg = 'Will shutdown the PC after 10 seconds'
        win32api.InitiateSystemShutdown(None, msg, 10, 1, 0)
        #InitiateSystemShutdown(computerName, message, timeOut, bForceClose, bRebootAfterShutdown)
        mlog(msg)

        break

    else:
        up = "Host %s is up" % vm_host
        mlog(up)
        print("-" * 60)
        time.sleep(
            d_time)  #if host is up, sleep d_time seconds, then detect again
Ejemplo n.º 29
0
 def reboot():
     logging.info("rebooting")
     win32api.InitiateSystemShutdown(None, None, 0, 1, 1)
Ejemplo n.º 30
0
def shutdown(
        message=None,
        timeout=5,
        force_close=True,
        reboot=False,  # pylint: disable=redefined-outer-name
        in_seconds=False,
        only_on_pending_reboot=False):
    '''
    Shutdown a running system.

    :param str message:
        A message to display to the user before shutting down.

    :param int timeout:
        The length of time that the shutdown dialog box should be displayed, in
        seconds. While this dialog box is displayed, the shutdown can be stopped
        by the shutdown_abort function.

        If timeout is not zero, InitiateSystemShutdown displays a dialog box on
        the specified computer. The dialog box displays the name of the user
        who called the function, displays the message specified by the
        lpMessage parameter, and prompts the user to log off. The dialog box
        beeps when it is created and remains on top of other windows in the
        system. The dialog box can be moved but not closed. A timer counts down
        the remaining time before a forced shutdown.

        If timeout is zero, the computer shuts down without displaying the
        dialog box, and the shutdown cannot be stopped by shutdown_abort.

        Default is 5 minutes

    :param bool in_seconds:
        Whether to treat timeout as seconds or minutes.

        .. versionadded:: 2015.8.0

    :param bool force_close:
        True to force close all open applications. False displays a dialog box
        instructing the user to close the applications.

    :param bool reboot:
        True restarts the computer immediately after shutdown.
        False caches to disk and safely powers down the system.

    :param bool only_on_pending_reboot:
        If this is set to True, then then shutdown will only proceed
        if the system reports a pending reboot.

    :return: True if successful (a shutdown or reboot will occur)
    :rtype: bool

    CLI Example:

    .. code-block:: bash

        salt '*' system.shutdown 5
    '''
    timeout = _convert_minutes_seconds(timeout, in_seconds)

    if only_on_pending_reboot and not get_pending_reboot():
        return False

    if message and not isinstance(message, str):
        message = message.decode('utf-8')
    try:
        win32api.InitiateSystemShutdown('127.0.0.1', message, timeout,
                                        force_close, reboot)
        return True
    except pywintypes.error as exc:
        (number, context, message) = exc
        log.error('Failed to shutdown the system')
        log.error('nbr: {0}'.format(number))
        log.error('ctx: {0}'.format(context))
        log.error('msg: {0}'.format(message))
        return False