Пример #1
0
def deal_data(conn, addr):
    print('已与 {0} 建立连接'.format(addr))
    data = conn.recv(1024)
    print('客户端 {0} 发送的数据是 {1}'.format(addr, data))
    if data == b'get_time':
        # 获取服务器本地时间
        localtime = win32api.GetLocalTime()  # tuple
        ctime = '{}-{}-{} {}:{}:{}'.format(
            localtime[0], localtime[1], localtime[3], localtime[4],
            localtime[5],
            localtime[6]).encode('utf8')  # tuple --> str --> bytes
    else:
        # 修改服务器本地时间
        wtime = datetime.strptime(data.decode('utf8'),
                                  '%Y-%m-%d %H:%M:%S') + timedelta(hours=8)
        win32api.SetLocalTime(wtime)
        ctime = data
    conn.send(ctime)
    conn.close()
Пример #2
0
    def _handle(self, cmd, param):
        """ Handle a received command.

        :type cmd: str
        :type param: List[T]
        :param cmd: command to handle
        :param param: list of parameters for command
        """
        self.logger.debug("adminpipe command: " + cmd)

        if cmd == "setostime":
            ptime = param[0]
            local_time = param[1]
            try:
                t = time.strptime(ptime, "%Y-%m-%d %H:%M:%S")
                self.logger.info("Trying to set time to: " + ptime)
            except ValueError:
                self.logger.error("Bad datetime format")
                return
            try:
                if local_time:
                    wt = pywintypes.Time(t)
                    rval = win32api.SetLocalTime(wt)  # you may prefer localtime
                else:
                    rval = win32api.SetSystemTime(t[0], t[1], t[6], t[2], t[3], t[4], t[5], 0)
                if rval == 0:
                    self.logger.error("Setting system time failed - function returned 0 - error code is {0}".format(
                        str(win32api.GetLastError())))
            except win32api.error:
                self.logger.error("Setting system time failed due to exception!")

        elif cmd == "runelevated":
            self.logger.debug("runelevated winadminagent")
            run = param[0]
            try:
                import subprocess
                import os
                subprocess.call(['runas', '/user:Administrator', os.system(run)])
            except Exception as e:
                self.logger.error(str(e))
Пример #3
0
    def _set_os_time(self, ptime, local_time=True):
        """
        Sets the systems time to the specifies date
            This may need admin rights on Windows

            :type local_time: bool
            :type ptime: str
            :param ptime: a posix date string in format "%Y-%m-%d %H:%M:%S"
            :param local_time: is this local time
        """
        try:
            t = time.strptime(ptime, "%Y-%m-%d %H:%M:%S")
            self.logger.info("Trying to set time to: " + ptime)
        except ValueError:
            self.logger.error("Bad datetime format")
            return
        if platform.system() == "Windows":
            try:
                if local_time:
                    wt = pywintypes.Time(t)
                    rval = win32api.SetLocalTime(
                        wt)  # you may prefer localtime
                else:
                    rval = win32api.SetSystemTime(t[0], t[1], t[6], t[2], t[3],
                                                  t[4], t[5], 0)
                if rval == 0:
                    self.logger.error(
                        "Setting system time failed - function returned 0 - error code is {0}"
                        .format(str(win32api.GetLastError())))
            except win32api.error:
                self.logger.error(
                    "Setting system time failed due to exception!")
        elif platform.system() == "Linux":
            pass  # todo: implement
        else:
            pass  # everything else unsupported
Пример #4
0
def set_system_date_time(years=None,
                         months=None,
                         days=None,
                         hours=None,
                         minutes=None,
                         seconds=None):
    '''
    Set the system date and time. Each argument is an element of the date, but
    not required. If an element is not passed, the current system value for that
    element will be used. For example, if you don't pass the year, the current
    system year will be used. (Used by set_system_date and set_system_time)

    :param int years: Years digit, ie: 2015
    :param int months: Months digit: 1 - 12
    :param int days: Days digit: 1 - 31
    :param int hours: Hours digit: 0 - 23
    :param int minutes: Minutes digit: 0 - 59
    :param int seconds: Seconds digit: 0 - 59

    :return: True if successful. Otherwise False.
    :rtype: bool

    CLI Example:

    .. code-block:: bash

        salt '*' system.set_system_date_ time 2015 5 12 11 37 53
    '''
    # Get the current date/time
    try:
        date_time = win32api.GetLocalTime()
    except win32api.error as exc:
        (number, context, message) = exc
        log.error('Failed to get local time')
        log.error('nbr: {0}'.format(number))
        log.error('ctx: {0}'.format(context))
        log.error('msg: {0}'.format(message))
        return False

    # Check for passed values. If not passed, use current values
    if not years:
        years = date_time[0]
    if not months:
        months = date_time[1]
    if not days:
        days = date_time[3]
    if not hours:
        hours = date_time[4]
    if not minutes:
        minutes = date_time[5]
    if not seconds:
        seconds = date_time[6]

    # Create the time tuple to be passed to SetLocalTime, including day_of_week
    time_tuple = (years, months, days, hours, minutes, seconds, 0)

    try:
        win32api.SetLocalTime(time_tuple)
    except win32api.error as exc:
        (number, context, message) = exc
        log.error('Failed to set local time')
        log.error('nbr: {0}'.format(number))
        log.error('ctx: {0}'.format(context))
        log.error('msg: {0}'.format(message))
        return False

    return True