Python threading.activeCount() Examples

The following are code examples for showing how to use threading.activeCount(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: Miscellaneous   Author: Shinpachi8   File: redis_monitor.py    Apache License 2.0 6 votes vote down vote up
def main():
    threads = []
    for i in xrange(30):
        t = Monitor()
        t.setDaemon = True
        threads.append(t)

    for t in threads:
        t.start()

    while True:
        try:
            if threading.activeCount() <= 1:
                break
            #time.sleep(10)
        except KeyboardInterrupt:
            Monitor.STOP_ME = True
            print "user killed and ready to exit"
            break
        except Exception as e:
            logger.error("monitor.main error for {}".repr(e)) 
Example 2
Project: py_banner_grabber   Author: surajsinghbisht054   File: bannergrab.py    Apache License 2.0 6 votes vote down vote up
def startthreading(self):
        listthread=[]
        for i in range(len(self.port)):
            storethread=threading.Thread(target=self.checkopenport)
            storethread.start()
            # Threead Controller
            if int(threading.activeCount())==int(self.thread):
                printingline="\r< IP : {} | Number of Threads : {} | Open Port Checking : {} | Open Ports Founded {} >".format(self.target,str(threading.activeCount()),str(i),str(len(self.store_open_ports)))
                sys.stdout.write(printingline)
                sys.stdout.flush()
                time.sleep(float(self.timeout))
            listthread.append(storethread)

        # Wait For All Thread
        for i in listthread:
            i.join()
        return (self.target, self.store_open_ports)

# Banner Grabbing Class 
Example 3
Project: py_banner_grabber   Author: surajsinghbisht054   File: bannergrab.py    Apache License 2.0 6 votes vote down vote up
def start_threading(self, address, port):
        listthread=[]
        for i in port:
            storethread=threading.Thread(target=self.banner_ip, args=(address, i,))
            storethread.start()
            if int(threading.activeCount())==int(self.thread):
                printingline="\r< IP : {} | Number of Threads : {} | Port : {}>".format(address, threading.activeCount(),i)
                sys.stdout.write(printingline)
                sys.stdout.flush()
                time.sleep(float(2))
            listthread.append(storethread)
        # Wait For All Threads
        for i in listthread:
            i.join()
        return

        # Banner Grabbing Functions 
Example 4
Project: smarthome   Author: smarthomeNG   File: smarthome.py    GNU General Public License v3.0 6 votes vote down vote up
def list_threads(self, txt):

        cp_threads = 0
        http_threads = 0
        for thread in threading.enumerate():
            if thread.name.find("CP Server") == 0:
                cp_threads += 1
            if thread.name.find("HTTPServer") == 0:
                http_threads +=1

        self._logger.info("list_threads: {} - Number of Threads: {} (CP Server={}, HTTPServer={}".format(txt, threading.activeCount(), cp_threads, http_threads))
        for thread in threading.enumerate():
            if thread.name.find("CP Server") != 0 and thread.name.find("HTTPServer") != 0:
                self._logger.info("list_threads: {} - Thread {}".format(txt, thread.name))
        return


    #################################################################
    # Item Methods
    ################################################################# 
Example 5
Project: F-Scrack   Author: lovesec   File: F-Scrack.py    GNU General Public License v3.0 6 votes vote down vote up
def t_join(m_count):
    tmp_count = 0
    i = 0
    if I < m_count:
        count = len(ip_list) + 1
    else:
        count = m_count
    while True:
        time.sleep(4)
        ac_count = threading.activeCount()
        #print ac_count,count
        if ac_count < count  and ac_count == tmp_count:
            i+=1
        else:
            i=0
        tmp_count = ac_count
        #print ac_count,queue.qsize()
        if (queue.empty() and threading.activeCount() <= 1) or i > 5:
            break 
Example 6
Project: harpoon   Author: evilhero   File: harpoon.py    GNU General Public License v3.0 6 votes vote down vote up
def daemonize(self):

        if threading.activeCount() != 1:
            logger.warn('There are %r active threads. Daemonizing may cause \
                            strange behavior.' % threading.enumerate())

        sys.stdout.flush()
        sys.stderr.flush()

        # Do first fork
        try:
            pid = os.fork()
            if pid == 0:
                pass
            else:
                # Exit the parent process
                logger.debug('Forking once...')
                os._exit(0)
        except OSError, e:
            sys.exit("1st fork failed: %s [%d]" % (e.strerror, e.errno)) 
Example 7
Project: MARA_Framework   Author: xtiankisutsa   File: pyssltest.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def status():
	ready = 0
	inva = 0
	errc = 0
	pend = 0
	print '\n' * 100
	for key in jobtrack:
			if jobtrack[key] =="Not Tested":
				pend = pend + 1
			elif jobtrack[key] =="Invalid":
				inva = inva + 1
			elif jobtrack[key] =="ERROR":
				errc = errc + 1
			elif jobtrack[key] =="READY":
				ready = ready + 1
	print "\n There are " + str(pend) + " pending"
	print "\n There are " + str(inva) + " Invalid"
	print "\n There are " + str(errc) + " errors"
	print "\n There are " + str(ready) + " ready"
	print "\n There are " + str(threading.activeCount()) + " Threads" 
Example 8
Project: snippets   Author: jeremiedecock   File: hello_meth1_with_lock.py    MIT License 6 votes vote down vote up
def main():
    """Main function"""

    lock = threading.Lock()

    thread1 = Foo(lock, iterations=10)
    thread2 = Foo(lock, iterations=15)

    thread1.start()
    thread2.start()

    # Let the main thread do something too...
    for i in range(5):
        lock.acquire()
        print threading.currentThread().name,
        print threading.currentThread().ident,
        print threading.activeCount(),
        print threading.enumerate()
        lock.release()
        time.sleep(0.2)

    # Main thread waits for all threads to complete
    thread1.join()
    thread2.join()
    print "Exiting Main Thread" 
Example 9
Project: snippets   Author: jeremiedecock   File: hello_meth2_with_lock.py    MIT License 6 votes vote down vote up
def main():
    """Main function"""

    lock = threading.Lock()

    thread1 = threading.Thread(target=foo, args=(lock, 10))
    thread2 = threading.Thread(target=foo, args=(lock, 15))

    thread1.start()
    thread2.start()

    # Let the main thread do something too...
    for i in range(5):
        lock.acquire()
        print threading.currentThread().name,
        print threading.currentThread().ident,
        print threading.activeCount(),
        print threading.enumerate()
        lock.release()
        time.sleep(0.2)

    # Main thread waits for all threads to complete
    thread1.join()
    thread2.join()
    print "Exiting Main Thread" 
Example 10
Project: pywikibot   Author: metakgp   File: weblinkchecker.py    MIT License 6 votes vote down vote up
def checkLinksIn(self, page):
        try:
            text = page.get()
        except pywikibot.NoPage:
            pywikibot.output(u'%s does not exist.' % page.title())
            return
        for url in weblinksIn(text):
            ignoreUrl = False
            for ignoreR in ignorelist:
                if ignoreR.match(url):
                    ignoreUrl = True
            if not ignoreUrl:
                # Limit the number of threads started at the same time. Each
                # thread will check one page, then die.
                while threading.activeCount() >= config.max_external_links:
                    # wait 100 ms
                    time.sleep(0.1)
                thread = LinkCheckThread(page, url, self.history,
                                         self.HTTPignore, self.day)
                # thread dies when program terminates
                thread.setDaemon(True)
                thread.start() 
Example 11
Project: test-framework-and-suites-for-android   Author: intel   File: common.py    Apache License 2.0 6 votes vote down vote up
def sync_run(self, serial, *methods):
        if isinstance(serial, list):
            serialList = serial
        elif isinstance(serial, str):
            serialList = serial.split(" ")

        __count_th = threading.activeCount()
        for deviceSerial in serialList:
            runThread = RunThread(
                self.__QUEUE__, deviceSerial, self.__CLASS_NAME__, methods)
            runThread.setDaemon(True)
            runThread.start()

        while True:
            if threading.activeCount() <= __count_th:
                break
            if self.__QUEUE__.qsize() > 0:
                raise Exception(self.__QUEUE__.get())
            time.sleep(0.2) 
Example 12
Project: pysoxy   Author: MisterDaneel   File: pysoxy.py    GNU General Public License v2.0 6 votes vote down vote up
def main():
    """ Main function """
    new_socket = create_socket()
    bind_port(new_socket)
    signal(SIGINT, exit_handler)
    signal(SIGTERM, exit_handler)
    while not EXIT.get_status():
        if activeCount() > MAX_THREADS:
            sleep(3)
            continue
        try:
            wrapper, _ = new_socket.accept()
            wrapper.setblocking(1)
        except socket.timeout:
            continue
        except socket.error:
            error()
            continue
        except TypeError:
            error()
            sys.exit(0)
        recv_thread = Thread(target=connection, args=(wrapper, ))
        recv_thread.start()
    new_socket.close() 
Example 13
Project: fancyMySQL   Author: cppla   File: fancyMysql.py    MIT License 6 votes vote down vote up
def putFileWork(fileName, bigChunkedFileDict, maxThread=MAX_THREAD):
    '''
    :param fileName: 文件名
    :param bigChunkedFileDict: 拆分的整个文件块
    :param maxThread: 最大线程
    :return:
    '''
    while len(bigChunkedFileDict):
        if threading.activeCount() < maxThread:
            t = threading.Thread(target=putFileThread, kwargs={'fileName': fileName, 'fileChunk': bigChunkedFileDict.popitem()})
            t.setDaemon(True)
            t.start()
        else:
            time.sleep(0.1)
    currentThread = threading.current_thread()
    for t in threading.enumerate():
        if t is currentThread:
            continue
        else:
            t.join() 
Example 14
Project: fancyMySQL   Author: cppla   File: fancyMysql.py    MIT License 6 votes vote down vote up
def getFileWork(fileName, filePath, splitCount, maxThread=MAX_THREAD):
    '''
    :param fileName: 文件名
    :param filePath: 文件写入路径
    :param splitCount: 文件总索引块数量
    :param maxThread: 最大线程
    :return:
    '''
    while splitCount:
        if threading.activeCount() < maxThread:
            t = threading.Thread(target=getFileThread, kwargs={'fileName': fileName, 'filePath': filePath, 'singleChunk': splitCount})
            splitCount = splitCount - 1
            t.setDaemon(True)
            t.start()
        else:
            time.sleep(0.1)
    currentThread = threading.currentThread()
    for t in threading.enumerate():
        if t is currentThread:
            continue
        else:
            t.join() 
Example 15
Project: LightUpPi-Alarm   Author: carlosperate   File: AlarmManager_test.py    MIT License 6 votes vote down vote up
def test_set_alarm_thread_edit(self):
        """
        Tests the __set_alarm_thread when an existing alarm thread is inputted.
        No need to check for input with wrong ID as that gets dealt with in the
        AlarmThread class and unit test.
        """
        first_alarm = AlarmItem(self.hour, 34, label='test', alarm_id=96,
                                days=(True, True, True, True, True, True, True),
                                enabled=True)
        new_alarm = AlarmItem(self.hour, 34, enabled=False, alarm_id=96,
                              label='test replace',
                              days=(False, False, False, False, False, False,
                                    False))
        alarm_mgr = AlarmManager()
        alarm_mgr.delete_all_alarms()
        numb_threads = threading.activeCount()
        launch_success = alarm_mgr._AlarmManager__set_alarm_thread(first_alarm)
        self.assertTrue(launch_success)
        self.assertGreater(threading.activeCount(), numb_threads)

        # Editing to the new alarm data should stop the thread as it is inactive
        launch_success = alarm_mgr._AlarmManager__set_alarm_thread(new_alarm)
        self.assertFalse(launch_success)
        self.assertEqual(threading.activeCount(), numb_threads) 
Example 16
Project: LightUpPi-Alarm   Author: carlosperate   File: AlarmManager_test.py    MIT License 6 votes vote down vote up
def test_stop_alarm_thread(self):
        """
        Test that the __stop_alarm_thread private method will stop a running
        Alarm Thread, which due to the nature of the thread code can take up to
        10 seconds.
        This test accesses private methods.
        """
        alarm = AlarmItem(self.hour, 34, enabled=True, label='t', alarm_id=96,
                          days=(False, True, True, True, True, True, True))
        alarm_mgr = AlarmManager()
        alarm_mgr.delete_all_alarms()
        numb_threads = threading.activeCount()
        launch_success = alarm_mgr._AlarmManager__set_alarm_thread(alarm)
        self.assertTrue(launch_success)
        self.assertGreater(threading.activeCount(), numb_threads)
        stop_success = alarm_mgr._AlarmManager__stop_alarm_thread(alarm.id_)
        self.assertTrue(stop_success)
        self.assertEqual(threading.activeCount(), numb_threads) 
Example 17
Project: LightUpPi-Alarm   Author: carlosperate   File: AlarmManager_test.py    MIT License 6 votes vote down vote up
def test_stop_all_alarm_threads(self):
        """
        Launches 2 alarms threads, checks they are running and them stops them
        all and checks again.
        """
        alarm_one = AlarmItem(
            self.hour, 34, enabled=True, alarm_id=31,
            days=(False, False, False, False, False, False, True))
        alarm_two = AlarmItem(
            self.hour, 34, enabled=True, alarm_id=32,
            days=(False, False, False, False, False, False, True))
        alarm_mgr = AlarmManager()
        # There is a bit of circular dependency here as delete all will execute
        # __stop_all_alarm_threads
        alarm_mgr.delete_all_alarms()
        launch_success = alarm_mgr._AlarmManager__set_alarm_thread(alarm_one)
        self.assertTrue(launch_success)
        launch_success = alarm_mgr._AlarmManager__set_alarm_thread(alarm_two)
        self.assertTrue(launch_success)
        numb_threads = threading.activeCount()
        self.assertGreaterEqual(numb_threads, 2)
        delete_success = alarm_mgr._AlarmManager__stop_all_alarm_threads()
        self.assertTrue(delete_success)
        self.assertEqual(threading.activeCount(), numb_threads - 2) 
Example 18
Project: Jery   Author: HewlettPackard   File: jery.py    GNU General Public License v2.0 6 votes vote down vote up
def QuitApps (self):
        """ Quit the main window procedure
            Before quitting, check if some toplevel windows still active.
                - If yes, ask to close them and do not leave the apps
                - if no, check if some threads still active:
                    - if yes: close them
                    - if no destroy the main window
        """

        if OpenToplevel == 0:
            nbthread = int(threading.activeCount())
            if nbthread > 2:
                self.OnButtonStopLoadClick()
            self.ProperStopApps()
        else:
            tkMessageBox.showinfo("Error", "Close the other windows first !") 
Example 19
Project: F-Scrack   Author: y1ng1996   File: F-Scrack.py    GNU General Public License v3.0 6 votes vote down vote up
def t_join(m_count):
    tmp_count = 0
    i = 0
    if I < m_count:
        count = len(ip_list) + 1
    else:
        count = m_count
    while True:
        time.sleep(4)
        ac_count = threading.activeCount()
        #print ac_count,count
        if ac_count < count  and ac_count == tmp_count:
            i+=1
        else:
            i=0
        tmp_count = ac_count
        #print ac_count,queue.qsize()
        if (queue.empty() and threading.activeCount() <= 1) or i > 5:
            break 
Example 20
Project: Sploits   Author: iDuronto   File: gtkcontroller.py    MIT License 6 votes vote down vote up
def update_counters_label(self):
        rem = str(self.moz.remaining())
        th_count = str(threading.activeCount()-1)
        if self._flying:
            work_count = str(len(self._flying.app.pool.workRequests))
            app = self._flying.app
            crawled = str(len(app.crawled_urls))+"/"+str(app.options.crawling)
        else:
            work_count = ""
            crawled = "X"
        pars = [crawled, rem, th_count, work_count]

        gtk.gdk.threads_enter()
        self.counters_label.set_text(" ".join(pars))
        if pars[3]:
            pars[3] = "\nworks in queue: %s"%(pars[3],)
        self.counters_label.set_tooltip_text('crawled during last attack: %s\nremaining checks: %s\nalive threads: %s %s' % tuple(pars))
        gtk.gdk.threads_leave() 
Example 21
Project: Sploits   Author: iDuronto   File: gtkcontroller.py    MIT License 6 votes vote down vote up
def update_counters_label(self):
        rem = str(self.moz.remaining())
        th_count = str(threading.activeCount()-1)
        if self._flying:
            work_count = str(len(self._flying.app.pool.workRequests))
            app = self._flying.app
            crawled = str(len(app.crawled_urls))+"/"+str(app.options.crawling)
        else:
            work_count = ""
            crawled = "X"
        pars = [crawled, rem, th_count, work_count]

        gtk.gdk.threads_enter()
        self.counters_label.set_text(" ".join(pars))
        if pars[3]:
            pars[3] = "\nworks in queue: %s"%(pars[3],)
        self.counters_label.set_tooltip_text('crawled during last attack: %s\nremaining checks: %s\nalive threads: %s %s' % tuple(pars))
        gtk.gdk.threads_leave() 
Example 22
Project: NiujiaoDebugger   Author: MrSrc   File: test_threading.py    GNU General Public License v3.0 5 votes vote down vote up
def test_old_threading_api(self):
        # Just a quick sanity check to make sure the old method names are
        # still present
        t = threading.Thread()
        t.isDaemon()
        t.setDaemon(True)
        t.getName()
        t.setName("name")
        t.isAlive()
        e = threading.Event()
        e.isSet()
        threading.activeCount() 
Example 23
Project: NiujiaoDebugger   Author: MrSrc   File: test_threading.py    GNU General Public License v3.0 5 votes vote down vote up
def test__all__(self):
        extra = {"ThreadError"}
        blacklist = {'currentThread', 'activeCount'}
        support.check__all__(self, threading, ('threading', '_thread'),
                             extra=extra, blacklist=blacklist) 
Example 24
Project: avocado-vt   Author: avocado-framework   File: virtio_console_guest.py    GNU General Public License v2.0 5 votes vote down vote up
def is_alive():
    """
    Check is only main thread is alive and if guest react.
    """
    if ((os_linux and (threading.activeCount() == 2)) or
            ((not os_linux) and (threading.activeCount() == 1))):
        print("PASS: Guest is ok no thread alive")
    else:
        threads = ""
        for thread in threading.enumerate():
            threads += thread.name + ", "
        print("FAIL: On guest run thread. Active thread:" + threads) 
Example 25
Project: dynamic-shard-updater   Author: brandonberney   File: main.py    GNU General Public License v2.0 5 votes vote down vote up
def _start(self):
        if threading.activeCount() is 2:
            print(constants.THREAD_RUNNING)
        else:
            self.thread = threading.Thread(target=follow.Follow,
                                           args=(self.directory, self.interval))
            self.thread.daemon = True
            self.thread.start()
            print(constants.THREAD_STARTED) 
Example 26
Project: dynamic-shard-updater   Author: brandonberney   File: main.py    GNU General Public License v2.0 5 votes vote down vote up
def do_status(self, args):
        if threading.activeCount() is 2:
            print(constants.THREAD_ONLINE)
        else:
            print(constants.THREAD_OFFLINE) 
Example 27
Project: Blockly-rduino-communication   Author: technologiescollege   File: test_threading.py    GNU General Public License v3.0 5 votes vote down vote up
def test_old_threading_api(self):
        # Just a quick sanity check to make sure the old method names are
        # still present
        t = threading.Thread()
        t.isDaemon()
        t.setDaemon(True)
        t.getName()
        t.setName("name")
        t.isAlive()
        e = threading.Event()
        e.isSet()
        threading.activeCount() 
Example 28
Project: SQLmap-Command-Builder   Author: kil-x   File: common.py    GNU General Public License v3.0 5 votes vote down vote up
def isMultiThreadMode():
    """
    Checks if running in multi-thread(ing) mode
    """

    return threading.activeCount() > 1 
Example 29
Project: subscraper   Author: m8r0wn   File: __init__.py    GNU General Public License v3.0 5 votes vote down vote up
def takeover(args, sublist, target):
    try:
        stdout.write("\n\033[1;30m[*] Subdomain Takeover Check\033[1;m\n")
        stdout.write("\033[1;30m{:<45}\t({:<9})\t{}\033[1;m\n".format('Subdomain', 'http/https', 'CNAME Record'))
        for sub in sublist:
            Thread(target=takeover_check, args=(sub, target,), daemon=True).start()
            while activeCount() > 15:
                sleep(0.001)
        while activeCount() > 1:
            sleep(0.005)

    except KeyboardInterrupt:
        stdout.write("\n[!] Key Event Detected...\n\n")
        return 
Example 30
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_threading.py    GNU General Public License v2.0 5 votes vote down vote up
def test_old_threading_api(self):
        # Just a quick sanity check to make sure the old method names are
        # still present
        t = threading.Thread()
        t.isDaemon()
        t.setDaemon(True)
        t.getName()
        t.setName("name")
        with self.assertWarnsRegex(PendingDeprecationWarning, 'use is_alive()'):
            t.isAlive()
        e = threading.Event()
        e.isSet()
        threading.activeCount() 
Example 31
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_threading.py    GNU General Public License v2.0 5 votes vote down vote up
def test__all__(self):
        extra = {"ThreadError"}
        blacklist = {'currentThread', 'activeCount'}
        support.check__all__(self, threading, ('threading', '_thread'),
                             extra=extra, blacklist=blacklist) 
Example 32
Project: python-duckling   Author: FraBle   File: duckling.py    Apache License 2.0 5 votes vote down vote up
def __init__(self,
                 jvm_started=False,
                 parse_datetime=False,
                 minimum_heap_size='128m',
                 maximum_heap_size='2048m'):
        """Initializes Duckling.
        """

        self.parse_datetime = parse_datetime
        self._is_loaded = False
        self._lock = threading.Lock()

        if not jvm_started:
            self._classpath = self._create_classpath()
            self._start_jvm(minimum_heap_size, maximum_heap_size)

        try:
            # make it thread-safe
            if threading.activeCount() > 1:
                if not jpype.isThreadAttachedToJVM():
                    jpype.attachThreadToJVM()
            self._lock.acquire()

            self.clojure = jpype.JClass('clojure.java.api.Clojure')
            # require the duckling Clojure lib
            require = self.clojure.var("clojure.core", "require")
            require.invoke(self.clojure.read("duckling.core"))
        finally:
            self._lock.release() 
Example 33
Project: ccsp   Author: pcuzner   File: rhs_usage.py    GNU General Public License v3.0 5 votes vote down vote up
def start_data_collection():

    # rrd database uses the config object for all settings
    rrd_db = RRDdatabase()
    if not rrd_db.db_usable:
        cfg.syslog.error("RRD database provided (%s) is not usable by rrd" % cfg.rrd_db)
        sys.exit(12)

    thread_list = []
    get_capacity_data = Collector(rrd_db, cfg.storage_type)

    cfg.syslog.info("Starting data collector")
    get_capacity_data.start()
    thread_list.append(get_capacity_data)

    if cfg.web_server in ['y', 'Y', 'Yes', 'YES']:
        cfg.syslog.info("Starting passive web interface")
        web_server = WebFrontEnd(cfg.web_root)
        web_server.start()
        thread_list.append(web_server)

    # threading.join starves the signal handler when you don't use
    # a timeout - consequently, the loop here uses a time out to make
    # sure we catch the stop request from upstart or systemd
    # ref: http://stackoverflow.com/questions/631441/interruptible-thread-join-in-python
    while threading.activeCount > 0:
        for thread in thread_list:
            thread.join(1) 
Example 34
Project: oss-ftp   Author: aliyun   File: servers.py    MIT License 5 votes vote down vote up
def _map_len(self):
            return threading.activeCount() 
Example 35
Project: oss-ftp   Author: aliyun   File: servers.py    MIT License 5 votes vote down vote up
def _map_len(self):
            return threading.activeCount() 
Example 36
Project: pythonprojects   Author: kurtlab   File: imagesmake.py    MIT License 5 votes vote down vote up
def downloadPic(self, urls, path):

        # 每过三秒检查一次当前正在运行的线程数,超标则沉睡等待线程结束
        while threading.activeCount() > 200:
            print("线程超标---%s" % threading.activeCount())
            time.sleep(3)

        for url in urls:
            if url:
                self.download(url, path) 
Example 37
Project: pythonprojects   Author: kurtlab   File: download_cl1024_images.py    MIT License 5 votes vote down vote up
def downloadPic(self, urls, path):

        # 每过三秒检查一次当前正在运行的线程数,超标则沉睡等待线程结束
        while threading.activeCount() > 5:
            print("线程超标---%s" % threading.activeCount())
            time.sleep(3)

        for url in urls:
            if url:
                print(url)
                self.download(url, path) 
Example 38
Project: allmyservos   Author: allmyservos   File: Resource.py    GNU General Public License v2.0 5 votes vote down vote up
def threads(self):
		""" track threads
		"""
		try:
			self.metrics['threadcount'].value = threading.activeCount()
			history = self.metrics['threadcount'].hotValues()
			if(len(history) > 1):
				if(history[-1].datavalue != self.metrics['threadcount'].value):
					self.metrics['threads'].value = self.__formatThreadData(threading.enumerate())
			else:
				self.metrics['threads'].value = self.__formatThreadData(threading.enumerate())
		except:
			pass 
Example 39
Project: Hot   Author: dsolimando   File: test_threading_jy.py    GNU General Public License v3.0 5 votes vote down vote up
def test_str_name(self):
        t = Thread(name=1)
        self.assertEqual(t.getName(), '1')
        t.setName(2)
        self.assertEqual(t.getName(), '2')

    # make sure activeCount() gets decremented (see issue 1348) 
Example 40
Project: Hot   Author: dsolimando   File: test_threading_jy.py    GNU General Public License v3.0 5 votes vote down vote up
def test_activeCount(self):
        activeBefore = threading.activeCount()
        activeCount = 10
        for i in range(activeCount):
            t = Thread(target=self._sleep, args=(i,))
            t.setDaemon(0)
            t.start()
        polls = activeCount
        while activeCount > activeBefore and polls > 0:
            time.sleep(1)
            activeCount = threading.activeCount()
            polls -= 1
        self.assertTrue(activeCount <= activeBefore, 'activeCount should to be <= %s, instead of %s' % (activeBefore, activeCount)) 
Example 41
Project: snippets   Author: jeremiedecock   File: hello_meth2.py    MIT License 5 votes vote down vote up
def foo(iterations):
    for i in range(iterations):
        print threading.currentThread().name,
        print threading.currentThread().ident,
        print threading.activeCount(),
        print threading.enumerate()
        time.sleep(0.2) 
Example 42
Project: snippets   Author: jeremiedecock   File: hello_meth1_with_lock.py    MIT License 5 votes vote down vote up
def run(self):
        for i in range(self._iterations):
            self._lock.acquire()
            print self.name,
            print self.ident,
            print threading.activeCount(),
            print threading.enumerate()
            self._lock.release()
            time.sleep(0.2) 
Example 43
Project: snippets   Author: jeremiedecock   File: hello_meth2_with_lock.py    MIT License 5 votes vote down vote up
def foo(lock, iterations):
    for i in range(iterations):
        lock.acquire()
        print threading.currentThread().name,
        print threading.currentThread().ident,
        print threading.activeCount(),
        print threading.enumerate()
        lock.release()
        time.sleep(0.2) 
Example 44
Project: gn-standalone   Author: yquant   File: subprocess2.py    Apache License 2.0 5 votes vote down vote up
def hack_subprocess():
  """subprocess functions may throw exceptions when used in multiple threads.

  See http://bugs.python.org/issue1731717 for more information.
  """
  global SUBPROCESS_CLEANUP_HACKED
  if not SUBPROCESS_CLEANUP_HACKED and threading.activeCount() != 1:
    # Only hack if there is ever multiple threads.
    # There is no point to leak with only one thread.
    subprocess._cleanup = lambda: None
    SUBPROCESS_CLEANUP_HACKED = True 
Example 45
Project: socks-proxy-tester   Author: DD-L   File: socks-proxy-test.py    MIT License 5 votes vote down vote up
def printr(self, msg):
        threads_count = 'jobs: '+ str(threading.activeCount()) + ', '
        progress = 'Completed: ' + self.get_progress()
        if msg == '':
            sys.stdout.write('\r' + threads_count + progress)
        else:
            sys.stdout.write('\r' + str(msg) + '\n' + threads_count + progress)
        sys.stdout.flush() 
Example 46
Project: photo-dl   Author: windrises   File: request.py    MIT License 5 votes vote down vote up
def put_request(self):
        global signal_flag
        generator = self.get_generator()
        while signal_flag:
            if threading.activeCount() < self.thread_size:
                url = next(generator, None)
                if url is None:
                    break
                thread = RequestThread(url['url'], url.get('info'), self.html_flag)
                thread.start()
                self.threads.append(thread)
                if self.progress:
                    print('\r[%d / %d] %s' % (self.count, len(self.urls), self.name), end='')
                self.count += 1 
Example 47
Project: node-gn   Author: Shouqun   File: subprocess2.py    MIT License 5 votes vote down vote up
def hack_subprocess():
  """subprocess functions may throw exceptions when used in multiple threads.

  See http://bugs.python.org/issue1731717 for more information.
  """
  global SUBPROCESS_CLEANUP_HACKED
  if not SUBPROCESS_CLEANUP_HACKED and threading.activeCount() != 1:
    # Only hack if there is ever multiple threads.
    # There is no point to leak with only one thread.
    subprocess._cleanup = lambda: None
    SUBPROCESS_CLEANUP_HACKED = True 
Example 48
Project: d4rkc0de   Author: knightmare2600   File: pyscan.py    GNU General Public License v2.0 5 votes vote down vote up
def scan(self, host, start, stop):
        self.port = start
        while self.port <= stop:
            while threading.activeCount() < MAX_THREADS:
                Scanner(host, self.port).start()
                self.port += 1 
Example 49
Project: lynder   Author: enescakir   File: lynder.py    MIT License 5 votes vote down vote up
def download_videos(tutorial):
    for chapter, lectures in tutorial["chapters"].items():
        os.chdir(chapter)
        for index, lecture in enumerate(lectures):
            while(threading.activeCount() > WORKER_NUM):
                time.sleep(5)
            th = Thread(target=download_lecture, args=(lecture,index,))
            th.deamon = True
            th.start()
            th.join()

        os.chdir("..")
    print("DOWNLOADING IS DONE")
    if arguments.silent is None:
        os.system("open .") 
Example 50
Project: tsocks   Author: jun7th   File: tsocks.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def exchange_data(self,sock,remote):#forward data
		global DEBUG
		try:
			inputs = [sock, remote]
			while True:
				r, w, e = select.select(inputs, [], [])
				if sock in r:
					if remote.send(sock.recv(BUF_SIZE)) <= 0:
						#sock.shutdown(socket.SHUT_RDWR)
						sock.close()
						#remote.shutdown(socket.SHUT_RDWR)
						remote.close()
						break
				if remote in r:
					if sock.send(remote.recv(BUF_SIZE)) <= 0:
						#sock.shutdown(socket.SHUT_RDWR)
						sock.close()
						#remote.shutdown(socket.SHUT_RDWR)
						remote.close()
						break
					if DEBUG:
						print "[*]Current active thread:",threading.activeCount()
						print "[*]Forwarding data..."
		except Exception,e:
			if DEBUG:
				print e
			sock.send("socket error")
			#remote.shutdown(socket.SHUT_RDWR)
			remote.close()
			#sock.shutdown(socket.SHUT_RDWR)
			sock.close() 
Example 51
Project: tsocks   Author: jun7th   File: tsocks.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def forward_translate(self,s,c):#port data exchange
		global BUF_SIZE
		global DEBUG
		try:
			conlist =[c,s]
			while True:
				r, w, e = select.select(conlist,[],[])
				if c in r:
					if s.send(c.recv(BUF_SIZE)) <=0:
						#c.shutdown(socket.SHUT_RDWR)
						c.close()
						#s.shutdown(socket.SHUT_RDWR)
						s.close()
						break
				if s in r:
					if c.send(s.recv(BUF_SIZE)) <=0:
						#s.shutdown(socket.SHUT_RDWR)
						s.close()
						#c.shutdown(socket.SHUT_RDWR)
						c.close()
						break
					if DEBUG:
						print "[*]Current active thread:",threading.activeCount()
						print "[*]Forwarding data..."
		except Exception,e:
			if DEBUG:
				print e
			#s.shutdown(socket.SHUT_RDWR)
			s.close()
			#c.shutdown(socket.SHUT_RDWR)
			c.close() 
Example 52
Project: S3-Version-Utilities   Author: vile8   File: s3_get_versioned_files_by_manifest.py    MIT License 5 votes vote down vote up
def isThreadPoolFull(self):
            global threadCountMax
            if(threading.activeCount() >= threadCountMax):
                debugPrintKey("Threading active count(boolean check against threadCountMax): " + str(threading.activeCount) + " : " + str(threadCountMax),3)
                return True
            else:
                return False 
Example 53
Project: S3-Version-Utilities   Author: vile8   File: s3_get_versioned_files_by_manifest.py    MIT License 5 votes vote down vote up
def isThreadPoolBusy(self):
            if(threading.activeCount() > 0):
                return True
            else:
                return False 
Example 54
Project: Project-New-Reign---Nemesis-Main   Author: ShikyoKira   File: test_threading.py    GNU General Public License v3.0 5 votes vote down vote up
def test_old_threading_api(self):
        # Just a quick sanity check to make sure the old method names are
        # still present
        t = threading.Thread()
        t.isDaemon()
        t.setDaemon(True)
        t.getName()
        t.setName("name")
        t.isAlive()
        e = threading.Event()
        e.isSet()
        threading.activeCount() 
Example 55
Project: darkc0de-old-stuff   Author: tuwid   File: pyscan.py    GNU General Public License v3.0 5 votes vote down vote up
def scan(self, host, start, stop):
        self.port = start
        while self.port <= stop:
            while threading.activeCount() < MAX_THREADS:
                Scanner(host, self.port).start()
                self.port += 1 
Example 56
Project: cells   Author: AlesTsurko   File: test_threading.py    MIT License 5 votes vote down vote up
def test_old_threading_api(self):
        # Just a quick sanity check to make sure the old method names are
        # still present
        t = threading.Thread()
        t.isDaemon()
        t.setDaemon(True)
        t.getName()
        t.setName("name")
        with self.assertWarnsRegex(PendingDeprecationWarning, 'use is_alive()'):
            t.isAlive()
        e = threading.Event()
        e.isSet()
        threading.activeCount() 
Example 57
Project: cells   Author: AlesTsurko   File: test_threading.py    MIT License 5 votes vote down vote up
def test__all__(self):
        extra = {"ThreadError"}
        blacklist = {'currentThread', 'activeCount'}
        support.check__all__(self, threading, ('threading', '_thread'),
                             extra=extra, blacklist=blacklist) 
Example 58
Project: LightUpPi-Alarm   Author: carlosperate   File: AlarmManager_test.py    MIT License 5 votes vote down vote up
def test_set_alarm_thread(self):
        """
        Test that the __set_alarm_thread private method will only launch an
        Alarm Thread if there is an active alarm.
        Ensure the thread has been launched successfully.
        This test accesses private methods.
        """
        alarm = AlarmItem(self.hour, 34,
                          days=(True, True, True, True, True, True, True),
                          enabled=False, label='test', alarm_id=96)
        alarm_mgr = AlarmManager()
        alarm_mgr.delete_all_alarms()
        numb_threads = threading.activeCount()

        # Test setting inactive alarm
        launch_success = alarm_mgr._AlarmManager__set_alarm_thread(alarm)
        self.assertFalse(launch_success)
        self.assertEqual(threading.activeCount(), numb_threads)

        # Test enabled alarm with no repeats
        alarm.repeat = (False, False, False, False, False, False, False)
        alarm.enabled = True
        launch_success = alarm_mgr._AlarmManager__set_alarm_thread(alarm)
        self.assertFalse(launch_success)
        self.assertEqual(threading.activeCount(), numb_threads)

        # Test fully active alarm
        alarm.wednesday = True
        launch_success = alarm_mgr._AlarmManager__set_alarm_thread(alarm)
        self.assertTrue(launch_success)
        self.assertGreater(threading.activeCount(), numb_threads) 
Example 59
Project: vitaproxy   Author: hrimfaxi   File: proxy_server.py    GNU General Public License v2.0 5 votes vote down vote up
def start_server():
    server_address = ("0.0.0.0", CONF['port'])
    proxy_handler.ProxyHandler.protocol_version = "HTTP/1.1"
    run_event = threading.Event()

    httpd = ThreadingHTTPServer(server_address, proxy_handler.ProxyHandler, CONF['cache'])
    sa = httpd.socket.getsockname()
    log.info("Download directory: %s", CONF['downloadDIR'])
    log.info("Servering HTTP on %s %s %s", sa[0], "port", sa[1])
    req_count = 0

    while not run_event.isSet():
        try:
            httpd.handle_request()
            req_count += 1
            if req_count == 1000:
                log.info("Number of active threads: %s", threading.activeCount())
                req_count = 0
        except select.error, e:
            if e[0] == 4 and run_event.isSet(): pass
            else:
                log.error("Errno: %d - %s", e[0], e[1])
        except socket.error as e:
            if e.errno == 10054:
                log.error("Connection reset by peer")
            else:
                log.error(str(e)) 
Example 60
Project: Jery   Author: HewlettPackard   File: jery.py    GNU General Public License v2.0 5 votes vote down vote up
def NbThread(self):
        nbthread = int(threading.activeCount())
        self.labelVariable2.set(" {0} active connections.".format(nbthread))
        #self.labelVariable.set(" {0} Valeur de OpenToplevel".format(OpenToplevel)) 
Example 61
Project: Jery   Author: HewlettPackard   File: jery.py    GNU General Public License v2.0 5 votes vote down vote up
def ProperStopApps(self):
        """ Wait for all threads to be shutdown before closing the apps.
        """
        nbthread = int(threading.activeCount())
        if nbthread > 2:
            self.labelVariable2.set("Loader shutdown ongoing. Still {0} active connections.".format(nbthread))
            self.after(1000, self.ProperStopApps)
        else:
            self.labelVariable2.set("Shutdown now!")
            self.after(500, self.destroy) 
Example 62
Project: galintools   Author: galindro   File: infra_common.py    GNU General Public License v2.0 5 votes vote down vote up
def active_count(self):
    return threading.activeCount() 
Example 63
Project: FCR   Author: facebookincubator   File: counters.py    MIT License 5 votes vote down vote up
def register_counters(cls, stats_mgr):
        stats_mgr.register_counter("sessions", CommandSession.get_session_count)
        stats_mgr.register_counter("gc.garbage", lambda: len(gc.garbage))
        stats_mgr.register_counter("active_threads", threading.activeCount)

        stats_mgr.register_counter(
            "cpu_usage_permille", lambda: round(cls._getCpuUsage() * 10)
        ) 
Example 64
Project: DDOS-RootSec   Author: R00tS3c   File: HellSecBotnet.py    GNU General Public License v3.0 5 votes vote down vote up
def begin():
        while True:
                if threading.activeCount() <= 666:
                        SlowLoris.start()				
# Request dame Server 
Example 65
Project: AutoHookSpider   Author: Tr3jer   File: main.py    GNU General Public License v3.0 5 votes vote down vote up
def run(self,*args):
		if args:
			self.entrances = args[0].split(',')
			for i in self.entrances:
				self.q.put('http://{}'.format(i))
		else:
			print '[+] Choose Entrances Domain ing ...'
			self.entrances = random.sample(self.hooks,self.thread_cnt)
			for i in self.entrances:
				if not port(i,80):
					self.reSelect(i)
				else:
					self.q.put('http://{}'.format(i))

		print "[+] Use : {}".format('、'.join(self.entrances))

		for t in xrange(self.thread_cnt):
			t = threading.Thread(target=self.req)
			t.setDaemon(True)
			t.start()

		while True:
			if threading.activeCount() <= 1:
				break
			else:
				try:
					time.sleep(0.1)
				except KeyboardInterrupt:
					self.STOP_ME = True
					raise 
Example 66
Project: invokust   Author: FutureSharks   File: lambda_load_test.py    MIT License 5 votes vote down vote up
def start_new_thread(self):
        '''
        Creates a new load test thread
        '''
        t_name = 'thread_{0}'.format(threading.activeCount())
        t = threading.Thread(name=t_name, target=self.thread)
        t.daemon = True
        t.start() 
Example 67
Project: sd-agent-core-plugins   Author: serverdensity   File: check.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def check(self, instance):

        if self.in_developer_mode:
            stats, names_to_metric_types = self._psutil_config_to_stats(instance)
            self._register_psutil_metrics(stats, names_to_metric_types)

        payload, context = self.get_metric_context()
        collection_time = context.get('collection_time', None)
        emit_time = context.get('emit_time', None)
        cpu_time = context.get('cpu_time', None)

        if threading.activeCount() > MAX_THREADS_COUNT:
            self.gauge('serverdensity.agent.collector.threads.count', threading.activeCount())
            self.log.info("Thread count is high: %d" % threading.activeCount())

        collect_time_exceeds_threshold = collection_time > MAX_COLLECTION_TIME
        if collection_time is not None and \
                (collect_time_exceeds_threshold or self.in_developer_mode):

            self.gauge('serverdensity.agent.collector.collection.time', collection_time)
            if collect_time_exceeds_threshold:
                self.log.info("Collection time (s) is high: %.1f, metrics count: %d, events count: %d",
                              collection_time, len(payload['metrics']), len(payload['events']))

        emit_time_exceeds_threshold = emit_time > MAX_EMIT_TIME
        if emit_time is not None and \
                (emit_time_exceeds_threshold or self.in_developer_mode):
            self.gauge('serverdensity.agent.emitter.emit.time', emit_time)
            if emit_time_exceeds_threshold:
                self.log.info("Emit time (s) is high: %.1f, metrics count: %d, events count: %d",
                              emit_time, len(payload['metrics']), len(payload['events']))

        if cpu_time is not None:
            try:
                cpu_used_pct = 100.0 * float(cpu_time)/float(collection_time)
                if cpu_used_pct > MAX_CPU_PCT:
                    self.gauge('serverdensity.agent.collector.cpu.used', cpu_used_pct)
                    self.log.info("CPU consumed (%%) is high: %.1f, metrics count: %d, events count: %d",
                                  cpu_used_pct, len(payload['metrics']), len(payload['events']))
            except Exception as e:
                self.log.debug("Couldn't compute cpu used by collector with values %s %s %s",
                               cpu_time, collection_time, str(e)) 
Example 68
Project: subscraper   Author: m8r0wn   File: __init__.py    GNU General Public License v3.0 4 votes vote down vote up
def subenum(args, target):
    try:
        stdout.write("\n\033[1;30m{:<13}\t{:<45}\t({:<9})\t{}\033[1;m\n".format('[Source]', 'Subdomain', 'http/https', 'DNS Resolution'))

        reporter = SubReporter(args)
        reporter.daemon = True
        reporter.start()
        handler = SubHandler(reporter.subq)

        for module in MODULES:
            module_class = get_module_class(module)
            class_obj    = module_class(args, target, handler)

            # Brute force methods
            if args.scrape and 'brute' in class_obj.method:
                Thread(target=class_obj.execute, args=(), daemon=True).start()

            # Scraping methods
            elif args.brute and 'scrape' in class_obj.method:
                Thread(target=class_obj.execute, args=(), daemon=True).start()

            while activeCount() > args.max_threads:
                sleep(0.001)

        while activeCount() > 2:
            sleep(0.005)
        reporter.stop()

        takeover(args, reporter.complete, target)
        return len(reporter.complete)

    except KeyboardInterrupt:
        try:
            reporter.close()
        except:
            pass

        stdout.write("\n[!] Key Event Detected...\n\n")
        return len(reporter.complete)

    except Exception as e:
        stdout.write("\033[1;30m{:<13}\t{:<25}\033[1;m\n".format('[Error-01]', str(e))) 
Example 69
Project: python-duckling   Author: FraBle   File: duckling.py    Apache License 2.0 4 votes vote down vote up
def parse(self, input_str, language=Language.ENGLISH, dim_filter=None, reference_time=''):
        """Parses datetime information out of string input.

        It invokes the Duckling.parse() function in Clojure.
        A language can be specified, default is English.

        Args:
            input_str: The input as string that has to be parsed.
            language: Optional parameter to specify language,
                e.g. Duckling.ENGLISH or supported ISO 639-1 Code (e.g. "en")
            dim_filter: Optional parameter to specify a single filter or
                list of filters for dimensions in Duckling.
            reference_time: Optional reference time for Duckling.

        Returns:
            A list of dicts with the result from the Duckling.parse() call.

        Raises:
            RuntimeError: An error occurres when Duckling model is not loaded
                via load().
        """
        if self._is_loaded is False:
            raise RuntimeError(
                'Please load the model first by calling load()')
        if threading.activeCount() > 1:
            if not jpype.isThreadAttachedToJVM():
                jpype.attachThreadToJVM()
        language = Language.convert_to_duckling_language_id(language)
        duckling_parse = self.clojure.var("duckling.core", "parse")
        duckling_time = self.clojure.var("duckling.time.obj", "t")
        clojure_hashmap = self.clojure.var("clojure.core", "hash-map")

        filter_str = '[]'
        if isinstance(dim_filter, string_types):
            filter_str = '[:{filter}]'.format(filter=dim_filter)
        elif isinstance(dim_filter, list):
            filter_str = '[{filter}]'.format(filter=' :'.join(dim_filter))
        if reference_time:
            duckling_result = duckling_parse.invoke(
                language,
                input_str,
                self.clojure.read(filter_str),
                clojure_hashmap.invoke(
                    self.clojure.read(':reference-time'),
                    duckling_time.invoke(
                        *self._parse_reference_time(reference_time))
                )
            )
        else:
            duckling_result = duckling_parse.invoke(
                language, input_str, self.clojure.read(filter_str))
        return self._parse_result(duckling_result) 
Example 70
Project: smarthome   Author: smarthomeNG   File: smarthome.py    GNU General Public License v3.0 4 votes vote down vote up
def stop(self, signum=None, frame=None):
        """
        This method is used to stop SmartHomeNG and all it's threads
        """
        self.shng_status = {'code': 31, 'text': 'Stopping'}

        self.alive = False
        self._logger.info("stop: Number of Threads: {}".format(threading.activeCount()))

        self.items.stop()
        self.scheduler.stop()
        if self.plugins is not None:
            self.plugins.stop()
        if self.modules is not None:
            self.modules.stop()
        self.connections.close()

        self.shng_status = {'code': 32, 'text': 'Stopping: Stopping threads'}

        for thread in threading.enumerate():
            if thread.name != 'Main':
                try:
                    thread.join(1)
                except Exception as e:
                    pass

        if threading.active_count() > 1:
            header_logged = False
            for thread in threading.enumerate():
                if thread.name != 'Main' and thread.name[0] !=  '_':
                    if not header_logged:
                        self._logger.warning("The following threads have not been terminated properly by their plugins (please report to the plugin's author):")
                        header_logged = True
                    self._logger.warning("-Thread: {}, still alive".format(thread.name))
            if header_logged:
                self._logger.warning("SmartHomeNG stopped")
        else:
            self._logger.warning("SmartHomeNG stopped")

        self.shng_status = {'code': 33, 'text': 'Stopped'}

        lib.daemon.remove_pidfile(PIDFILE)

        logging.shutdown()
        exit() 
Example 71
Project: OXIDTools   Author: oxyda-fox   File: mbf.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def crack0(data,sandi,p):
	tampil('\rh[*]MengCrack \rk%d Akun \rhdengan sandi \rm[\rk%s\rm]'%(len(data),sandi))
	print('\033[32;1m[*]Cracking \033[31;1m[\033[36;1m0%\033[31;1m]\033[0m',end='')
	os.sys.stdout.flush()
	akun_jml = []
	akun_sukses = []
	akun_cekpoint = []
	akun_error = []
	akun_gagal = []
	jml0,jml1 = 0,0
	th = []
	for i in data:
		i = i.replace(' ','')
		if len(i) != 0:th.append(mt(i,sandi))
	for i in th:
		jml1 += 1
		i.daemon = True
		try:i.start()
		except KeyboardInterrupt:exit()
	while 1:
		try:
			for i in th:
				a = i.update()
				if a[0] != 3 and a[1] not in akun_jml:
					jml0 += 1
					if a[0] == 2:
						akun_cekpoint.append(a[1])
					elif a[0] == 1:
						akun_sukses.append(a[1])
					elif a[0] == 0:
						akun_gagal.append(a[1])
					elif a[0] == 8:
						akun_error.append(a[1])
					print('\r\033[32;1m[*]Cracking \033[31;1m[\033[36;1m%0.2f%s\033[31;1m]\033[0m'%(float((float(jml0)/float(jml1))*100),'%'),end='')
					os.sys.stdout.flush()
					akun_jml.append(a[1])
		except KeyboardInterrupt:
			os.sys.exit()
		try:
			if threading.activeCount() == 1:break
		except KeyboardInterrupt:
			keluar()
	print('\r\033[32;1m[*]Cracking \033[31;1m[\033[36;1m100%\033[31;1m]\033[0m     ')
	if len(akun_sukses) != 0:
		tampil('\rh[*]Daftar akun sukses')
		for i in akun_sukses:
			tampil('\rh==>\rk%s \rm[\rp%s\rm]'%(i,sandi))
	tampil('\rh[*]Jumlah akun berhasil\rp      %d'%len(akun_sukses))
	tampil('\rm[*]Jumlah akun gagal\rp         %d'%len(akun_gagal))
	tampil('\rk[*]Jumlah akun cekpoint\rp      %d'%len(akun_cekpoint))
	tampil('\rc[*]Jumlah akun error\rp         %d'%len(akun_error))
	if p:
		i = inputD('[?]Tidak Puas dengan Hasil,Mau coba lagi (y/t)',['Y','T'])
		if i.upper() == 'Y':
			return crack(data)
		else:
			return menu()
	else:
		return 0 
Example 72
Project: Plex-CS   Author: zobe123   File: __init__.py    GNU General Public License v3.0 4 votes vote down vote up
def daemonize():
    if threading.activeCount() != 1:
        logger.warn(
            'There are %r active threads. Daemonizing may cause'
            ' strange behavior.',
            threading.enumerate())

    sys.stdout.flush()
    sys.stderr.flush()

    # Do first fork
    try:
        pid = os.fork()  # @UndefinedVariable - only available in UNIX
        if pid != 0:
            sys.exit(0)
    except OSError as e:
        raise RuntimeError("1st fork failed: %s [%d]", e.strerror, e.errno)

    os.setsid()

    # Make sure I can read my own files and shut out others
    prev = os.umask(0)  # @UndefinedVariable - only available in UNIX
    os.umask(prev and int('077', 8))

    # Make the child a session-leader by detaching from the terminal
    try:
        pid = os.fork()  # @UndefinedVariable - only available in UNIX
        if pid != 0:
            sys.exit(0)
    except OSError as e:
        raise RuntimeError("2nd fork failed: %s [%d]", e.strerror, e.errno)

    dev_null = file('/dev/null', 'r')
    os.dup2(dev_null.fileno(), sys.stdin.fileno())

    si = open('/dev/null', "r")
    so = open('/dev/null', "a+")
    se = open('/dev/null', "a+")

    os.dup2(si.fileno(), sys.stdin.fileno())
    os.dup2(so.fileno(), sys.stdout.fileno())
    os.dup2(se.fileno(), sys.stderr.fileno())

    pid = os.getpid()
    logger.info('Daemonized to PID: %d', pid)

    if CREATEPID:
        logger.info("Writing PID %d to %s", pid, PIDFILE)
        with file(PIDFILE, 'w') as fp:
            fp.write("%s\n" % pid) 
Example 73
Project: mbf   Author: Viole403   File: mbf.py    Apache License 2.0 4 votes vote down vote up
def crack0(data,sandi):
	akun = []
	cetak('!h[*] MengCrack !k%d Akun !hdengan sandi !m[!k%s!m]'%(len(data),sandi))
	cetak('!h[*] Cracking  !k0!m%',1)
	sys.stdout.flush()
	jml0,jml1 = 0,0
	th = []
	for i in data:
		i = i.replace(' ','')
		i = i.replace('\n','')
		if len(i) != 0:th.append(mt(i,sandi))
		jml1 += 1
	for i in th:
		i.daemon = True
		try:i.start()
		except KeyboardInterrupt:exit()
	h_error = []
	error = 0
	while 1:
		try:
			for i in th:
				status,id = i.update()
				if status != 0:
					cetak('\r!h[*] Cracking  !k%d!m%s!0'%(int(float((float(jml0)/float(jml1))*100)),'%'),1)
					sys.stdout.flush()
					del(th[th.index(i)])
					if status == 4:
						h_error.append(id)
						if h_error.count(id) == 3:
							pass
						else:
							th.append(mt(id,sandi))
							th[len(th)-1].daemon = True
							th[len(th)-1].start()
					else:
						jml0 += 1
						akun.append((status,id))
		except KeyboardInterrupt:
			sys.exit()
		try:
			if threading.activeCount() == 1:break
		except KeyboardInterrupt:
			keluar()
	cetak('\r!h[*] Cracking  !k100!m%      ')
	tampilhasil(akun,sandi) 
Example 74
Project: BAJINGANv6   Author: DarknessCyberTeam   File: mbf.py    Apache License 2.0 4 votes vote down vote up
def crack0(data,sandi,p):
	tampil('\rh[*]MengCrack \rk%d Akun \rhdengan sandi \rm[\rk%s\rm]'%(len(data),sandi))
	print('\033[32;1m[*]Cracking \033[31;1m[\033[36;1m0%\033[31;1m]\033[0m',end='')
	os.sys.stdout.flush()
	akun_jml = []
	akun_sukses = []
	akun_cekpoint = []
	akun_error = []
	akun_gagal = []
	jml0,jml1 = 0,0
	th = []
	for i in data:
		i = i.replace(' ','')
		if len(i) != 0:th.append(mt(i,sandi))
	for i in th:
		jml1 += 1
		i.daemon = True
		try:i.start()
		except KeyboardInterrupt:exit()
	while 1:
		try:
			for i in th:
				a = i.update()
				if a[0] != 3 and a[1] not in akun_jml:
					jml0 += 1
					if a[0] == 2:
						akun_cekpoint.append(a[1])
					elif a[0] == 1:
						akun_sukses.append(a[1])
					elif a[0] == 0:
						akun_gagal.append(a[1])
					elif a[0] == 8:
						akun_error.append(a[1])
					print('\r\033[32;1m[*]Cracking \033[31;1m[\033[36;1m%0.2f%s\033[31;1m]\033[0m'%(float((float(jml0)/float(jml1))*100),'%'),end='')
					os.sys.stdout.flush()
					akun_jml.append(a[1])
		except KeyboardInterrupt:
			os.sys.exit()
		try:
			if threading.activeCount() == 1:break
		except KeyboardInterrupt:
			keluar()
	print('\r\033[32;1m[*]Cracking \033[31;1m[\033[36;1m100%\033[31;1m]\033[0m     ')
	if len(akun_sukses) != 0:
		tampil('\rh[*]Daftar akun sukses')
		for i in akun_sukses:
			tampil('\rh==>\rk%s \rm[\rp%s\rm]'%(i,sandi))
	tampil('\rh[*]Jumlah akun berhasil\rp      %d'%len(akun_sukses))
	tampil('\rm[*]Jumlah akun gagal\rp         %d'%len(akun_gagal))
	tampil('\rk[*]Jumlah akun cekpoint\rp      %d'%len(akun_cekpoint))
	tampil('\rc[*]Jumlah akun error\rp         %d'%len(akun_error))
	if p:
		i = inputD('[?]Tidak Puas dengan Hasil,Mau coba lagi (y/t)',['Y','T'])
		if i.upper() == 'Y':
			return crack(data)
		else:
			return menu()
	else:
		return 0 
Example 75
Project: B4J1N64Nv4   Author: DarknessCyberTeam   File: mbf.py    Apache License 2.0 4 votes vote down vote up
def crack0(data,sandi,p):
	tampil('\rh[*]MengCrack \rk%d Akun \rhdengan sandi \rm[\rk%s\rm]'%(len(data),sandi))
	print('\033[32;1m[*]Cracking \033[31;1m[\033[36;1m0%\033[31;1m]\033[0m',end='')
	os.sys.stdout.flush()
	akun_jml = []
	akun_sukses = []
	akun_cekpoint = []
	akun_error = []
	akun_gagal = []
	jml0,jml1 = 0,0
	th = []
	for i in data:
		i = i.replace(' ','')
		if len(i) != 0:th.append(mt(i,sandi))
	for i in th:
		jml1 += 1
		i.daemon = True
		try:i.start()
		except KeyboardInterrupt:exit()
	while 1:
		try:
			for i in th:
				a = i.update()
				if a[0] != 3 and a[1] not in akun_jml:
					jml0 += 1
					if a[0] == 2:
						akun_cekpoint.append(a[1])
					elif a[0] == 1:
						akun_sukses.append(a[1])
					elif a[0] == 0:
						akun_gagal.append(a[1])
					elif a[0] == 8:
						akun_error.append(a[1])
					print('\r\033[32;1m[*]Cracking \033[31;1m[\033[36;1m%0.2f%s\033[31;1m]\033[0m'%(float((float(jml0)/float(jml1))*100),'%'),end='')
					os.sys.stdout.flush()
					akun_jml.append(a[1])
		except KeyboardInterrupt:
			os.sys.exit()
		try:
			if threading.activeCount() == 1:break
		except KeyboardInterrupt:
			keluar()
	print('\r\033[32;1m[*]Cracking \033[31;1m[\033[36;1m100%\033[31;1m]\033[0m     ')
	if len(akun_sukses) != 0:
		tampil('\rh[*]Daftar akun sukses')
		for i in akun_sukses:
			tampil('\rh==>\rk%s \rm[\rp%s\rm]'%(i,sandi))
	tampil('\rh[*]Jumlah akun berhasil\rp      %d'%len(akun_sukses))
	tampil('\rm[*]Jumlah akun gagal\rp         %d'%len(akun_gagal))
	tampil('\rk[*]Jumlah akun cekpoint\rp      %d'%len(akun_cekpoint))
	tampil('\rc[*]Jumlah akun error\rp         %d'%len(akun_error))
	if p:
		i = inputD('[?]Tidak Puas dengan Hasil,Mau coba lagi (y/t)',['Y','T'])
		if i.upper() == 'Y':
			return crack(data)
		else:
			return menu()
	else:
		return 0 
Example 76
Project: OregonState_DLM   Author: OSU-Geomatics   File: COMLogger.py    GNU General Public License v3.0 4 votes vote down vote up
def run(argv):
    # Parse arguments
    nargs = len(argv)
    div, mod = divmod(nargs, 2)
    if mod == 0 and div > 1:
        filename = argv[1]
        comports = []
        baudrates = []
        for iarg in range(2, nargs, 2):
            comports.append(argv[iarg])
            baudrates.append(int(argv[iarg+1]))
    else:
        print("Wrong Number of Inputs")
        print("Option 1: COMLogger.exe COM1 9600")
        print("Option 2: COMLogger.exe COM1 9600 COM2 9600 ... etc")

        return 0

    writeLock = threading.Lock()
    keepWriting = [True]
    allThreads = []
    f = open(filename, "w")
    print("Opened " + filename)
    initialthreadnum = threading.activeCount()
    for port, baud in zip(comports, baudrates):
        iThread = threading.Thread(target=writeSerial, args=(port, baud, f, writeLock, keepWriting))
        iThread.daemon = True
        iThread.start()
        allThreads.append(iThread)

    time.sleep(0.1)

    while keepWriting[0]:
        key = input('Press "Q", then "Enter" to end logging: ')
        if key == "Q" or key == "q":
            keepWriting[0] = False
            print("Received request to close file")

    print("Waiting for writing operations to finish")
    while initialthreadnum != threading.activeCount():
        print("Number of Threads Still Alive: " + str(threading.activeCount() - initialthreadnum))
        time.sleep(0.25)

    print("Closing File")
    f.close() 
Example 77
Project: fancyDownload   Author: cppla   File: fancyDownload.py    MIT License 4 votes vote down vote up
def getFileWork(objectFileUrl, objectFilePath, objectSession):
    '''

    :param objectFileUrl: 请求链接
    :param objectFilePath: 目标存储路径
    :param objectSession: 验证头
    :return:
    '''
    r = requests.head(objectFileUrl)
    if r.status_code in [301, 302]:
        r = requests.head(r.headers['Location'])

    if r.status_code in [404, 501, 502, 503]:
        print(u'服务器异常,返回码: %d' % r.status_code)
        return
    elif r.status_code in [401]:
        print(u'服务器需要鉴权,返回码: %d' % r.status_code)
        return

    if 'Content-Length' in r.headers:
        objectFileSize = int(r.headers['Content-Length'])

        with open(objectFilePath, "wb") as f:
            f.truncate(objectFileSize)

        splitCount = int(objectFileSize/SPLIT_SIZE) + 1
        while splitCount:
            if threading.activeCount() < MAX_THREAD:
                t = threading.Thread(
                    target=getFileThread,
                    kwargs={
                        'objectFileUrl': objectFileUrl,
                        'objectFilePath': objectFilePath,
                        'objectSession': objectSession,
                        'singleChunk': splitCount
                    }
                )
                splitCount = splitCount - 1
                t.setDaemon(True)
                t.start()
            else:
                time.sleep(0.1)
        currentThread = threading.currentThread()
        for t in threading.enumerate():
            if t is currentThread:
                continue
            else:
                t.join()
    else:
        headers = objectSession
        headers["User-Agent"] = "Mozilla/5.0 (compatible; fancyDownload/1.1; +https://github.com/cppla/fancyDownload)"

        r = requests.get(
            url=objectFileUrl,
            headers=headers,
            stream=True
        )
        with open(objectFilePath, "wb+") as f:
            for chunk in r.iter_content(chunk_size=SPLIT_SIZE):
                if chunk:
                    f.write(chunk) 
Example 78
Project: LightUpPi-Alarm   Author: carlosperate   File: HardwareThread_test.py    MIT License 4 votes vote down vote up
def test_multirun(self):
        """
        Tests that the HardwareThread can be launched several times and that
        if one instance launches the thread, and another tries to do the same it
        will wait until it is done.
        This test can take over 8 seconds (2s per thread launch, 4 launches)
        """
        # These thread last 2 seconds
        hw_thread_instance_one = HardwareThread(
            lamp=(0, 1), room_light=(0, 1), coffee_time=0, total_time=2)
        hw_thread_instance_two = HardwareThread()

        # Mocking the hardware threads, they will finish as soon as they are
        # launched
        def mock_hw(cls):
            pass
        HardwareThread._launch_lamp = \
            types.MethodType(mock_hw, HardwareThread)
        HardwareThread._launch_room_light = \
            types.MethodType(mock_hw, HardwareThread)
        HardwareThread._launch_coffee = \
            types.MethodType(mock_hw, HardwareThread)

        # Launch the hardware thread, ensure it lasts 2 seconds
        start_time = time.time()
        hw_thread_instance_one.start()
        while hw_thread_instance_one.isAlive():
            pass
        end_time = time.time()
        self.assertAlmostEqual(2, end_time - start_time, delta=0.1)

        # Ensure the hardware thread can be launched multiple times
        start_time = time.time()
        hw_thread_instance_one.start()
        while hw_thread_instance_one.isAlive():
            pass
        end_time = time.time()
        self.assertAlmostEqual(2, end_time - start_time, delta=0.1)

        # Ensure the hardware thread can only be launched once at a time
        original_numb_threads = threading.activeCount()
        start_time = time.time()

        hw_thread_instance_one.start()
        time.sleep(0.2)  # Enough time for child threads launch and end
        hw_thread_count = threading.activeCount()
        self.assertEqual(original_numb_threads + 1, hw_thread_count)

        hw_thread_instance_two.start()
        self.assertEqual(hw_thread_count, threading.activeCount())
        while hw_thread_instance_two.isAlive():
            pass

        end_time = time.time()
        self.assertAlmostEqual(2*2, end_time - start_time, delta=0.1*2) 
Example 79
Project: Jery   Author: HewlettPackard   File: jery.py    GNU General Public License v2.0 4 votes vote down vote up
def run(self):
        i = 1
        while self.runWatch != 1:
            try:
                if self.EntryConUsers.get() and self.EntryConUsers.get().isdigit() and int(self.EntryConUsers.get()) >= 1:
                    try:
                        ConcUsers = int(self.EntryConUsers.get())
                        noActiveOraThreads = int(threading.activeCount()) -2
                        # print "------------------------------------------"
                        # print "ConcUsers: " + str(ConcUsers)
                        # print "noActiveOraThreads: " + str(noActiveOraThreads)

                        while len(self.existingThread)-1 < ConcUsers:
                            i += 1
                            self.my_thread = LoadThread(str(self.Entry3.get()), str(self.Entry4.get()), str(self.Entry5.get()),
                                                        str(self.Entry1.get()), str(self.Entry2.get()),
                                                        int(self.EntryTestLength.get()))
                            self.my_thread.name = i
                            self.my_thread.start()
                            self.existingThread.append(self.my_thread)
                            # time.sleep(1)
                            # self.after(500, self.labelVariable.set("Number of Thread: "+str(threading.activeCount())))


                        while len(self.existingThread)-1 > ConcUsers and self.existingThread:
                                i -= 1
                                lastThread = self.existingThread.pop()
                                if lastThread.isAlive():
                                    lastThread.stopThread()


                        #check if thrad is alive. If thread died -> restart a new one
                        for thread in self.existingThread:
                            #sys.stdout.write("X ")
                            #sys.stdout.flush()
                            if not thread.isAlive():
                                print str(thread) + "  died. Restarting..."
                                self.existingThread.remove(thread)
                        #sys.stdout.write("\n")

                        ActiveUsers = len(self.existingThread)-1
                        self.labelVariable.set("Number of active users: " + str(ActiveUsers))

                        # print self.existingThread
                        # print "\n"
                    except ValueError:
                        print "Value Error"
                else:
                    self.labelVariable.set("Please enter a valid number of users")
            except TclError:
                print "TclError"



            time.sleep(1) 
Example 80
Project: sshpwn   Author: Optixal   File: sshpwn.py    MIT License 4 votes vote down vote up
def main():

    try:
        greets()
        loadconfig()

        while True:
            targets = gettargetlist()
            if not targets:
                continue

            style3 = cs.center_fade(232, 256, "\xBB", 65, 0.04)
            style3.animate()

            while True:
                sshpwncmd = input(cs.sshpwncaret)
                sshpwntokens = sshpwncmd.split(" ", 1)

                builtincmdcode, targets = builtincmd(sshpwntokens, targets)
                if builtincmdcode == 1:
                    break
                elif builtincmdcode == 2:
                    print()
                    continue
                elif builtincmdcode == 3:
                    # No command typed in
                    continue

                # Refresh targets before executing command, if MissionCriticalMode is on
                if missioncritical:
                    targets = refreshtargets(targets)
                    if len(targets) == 0:
                        print(cs.error, "Unable to connect to any user!")
                        break

                execute(sshpwntokens, targets)

                print()

    except KeyboardInterrupt:
        print("\n" + cs.status, "Exiting...")
        #if configs["DebugMode"] == "on":
        #    print(cs.status, "Active thread count:", threading.activeCount())