コード例 #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)
コード例 #2
0
def win_shutdown():
    """ Shutdown Windows system, never returns """
    try:
        win_power_privileges()
        win32api.InitiateSystemShutdown("", "", 30, 1, 0)
    finally:
        os._exit(0)
コード例 #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)
コード例 #4
0
ファイル: recipe-360649.py プロジェクト: kaestnja/pystrict3
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)
コード例 #5
0
ファイル: reboot.py プロジェクト: kimcon7775/vehicles
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)
コード例 #6
0
ファイル: test.py プロジェクト: selidri/Black-Hat-Python
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}")
コード例 #7
0
def initpc(flag):
    if flag == 1:
        try:
            win32api.InitiateSystemShutdown('localhost',
                                            '即将重启云桌面,重启后打开计算机重新授权,选择完全允许读写', 5,
                                            True, True)
        except Exception as e:
            print(e)
コード例 #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)
コード例 #9
0
ファイル: __init__.py プロジェクト: dnz3d4c/systemShutdown
 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)
コード例 #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
コード例 #11
0
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)
コード例 #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)
コード例 #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
コード例 #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
コード例 #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
コード例 #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)
コード例 #17
0
ファイル: powersup.py プロジェクト: TinyHTPC/xbmc-dev-repo
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)
コード例 #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
コード例 #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
コード例 #20
0
ファイル: reboot.py プロジェクト: xits-coders/wpkg-gp
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
コード例 #21
0
ファイル: RebootService.py プロジェクト: guozanhua/maestro
 def Reboot(message="Rebooting", timeout=30, bForce=0, bReboot=1):
     AdjustPrivilege(SE_SHUTDOWN_NAME)
     win32api.InitiateSystemShutdown(None, message, timeout, bForce,
                                     bReboot)
コード例 #22
0
 def reboot():
     print("rebooting")
     win32api.InitiateSystemShutdown(None, None, 0, 1, 1)
コード例 #23
0
ファイル: watch_reboot.py プロジェクト: thomassa/xenrt
    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")
コード例 #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.')
コード例 #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
コード例 #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
コード例 #27
0
ファイル: shutdown.py プロジェクト: wingsof/trader
def go_shutdown(is_reboot=0):
    AdjustPrivilege(SE_SHUTDOWN_NAME)
    win32api.InitiateSystemShutdown(None, 'Shutdown msg from API Server', 10,
                                    1, is_reboot)
コード例 #28
0
ファイル: esxi_rel2.py プロジェクト: Bulel/manage-ESXI
            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
コード例 #29
0
ファイル: test_cabsagent.py プロジェクト: jeason-j/cabs
 def reboot():
     logging.info("rebooting")
     win32api.InitiateSystemShutdown(None, None, 0, 1, 1)
コード例 #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