-1

i'm trying to limit this loop to 4 concurrent jobs:

def testSSH(host, user, password, port):
s = pxssh.pxssh()
try:
    if not s.login (host, username=user, password=password, port=port):
        print(password)
        return False
    else:
        print(password)
        return True
except:
    print(password)
    return False




passes = "r", "1234", "12345", "123456!", "1234567", "a", "b", "e", "s", "A", "d", "66"

jobs = []
for passw in passes:
    thread = threading.Thread(target=testSSH, args=("localhost", "myuser", passw, "22",))
    jobs.append(thread)

for j in jobs:
        print(threading.active_count())
        j.start()

for j in jobs:
        j.join()

the code runs fine. however, i cannot seem to limit the concurrent jobs. the threading.active_count() is always the value of passes. any tips? i've tried this question but could make little of it thanks!

Benny
  • 695
  • 2
  • 6
  • 19
  • for limiting the resources like this, would you consider using [semaphores](https://docs.python.org/3/library/threading.html#semaphore-objects)? – adrtam Mar 11 '19 at 18:53
  • Possible duplicate of [The right way to limit maximum number of threads running at once?](https://stackoverflow.com/questions/19369724/the-right-way-to-limit-maximum-number-of-threads-running-at-once) – elemakil Mar 11 '19 at 18:53
  • can you send an example of using semaphores in a code like this one? – Benny Mar 11 '19 at 19:01

1 Answers1

1

OK guys, found something myself:

threads = 0
def testSSH(host, user, password, port):
s = pxssh.pxssh()
try:
    if not s.login (host, username=user, password=password, port=port):
        print(password)
        return False
    else:
        print(password)
        return True
except:
    print(password)
    return False




passes = "r", "1234", "12345", "123456!", "1234567", "a", "b", "e", "s", "A", "d", "66"

jobs = []
for passw in passes:
    thread = threading.Thread(target=testSSH, args=("localhost", "myuser", passw, "22",))
    jobs.append(thread)

for j in jobs:
    threads = threading.active_count()
    while threads > 4:
    time.sleep(0.05)
    threads = threading.active_count()
        j.start()

for j in jobs:
        j.join()

hope this helps someone down the road...

Benny
  • 695
  • 2
  • 6
  • 19