Advertisement
aex-

Thread Limiter Example

Feb 24th, 2018
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.89 KB | None | 0 0
  1. import os
  2. import sys
  3. import socket
  4. import threading
  5. import random
  6.  
  7. thread_limit = 100
  8. thread_start = 0
  9. thread_id = []
  10. syntax = '!'
  11.  
  12. def get_thread_id():
  13.     tid = random.randint(1, 100)
  14.     thread_id.append(tid)
  15.     return tid
  16.  
  17. def client(conn, addr, tid):
  18.     global thread_start
  19.     global thread_limit
  20.     global thread_id
  21.     global syntax
  22.  
  23.     try:
  24.         conn.send("[server] session assigned with thread id %s\r\n" % (tid))
  25.         conn.send("cmd> ")
  26.         cmd = conn.recv(512)
  27.         if (len(cmd) > 512):
  28.             conn.close()
  29.             print("[client] client sent a string longer than recv limit")
  30.             thread_start -= 1
  31.  
  32.         ncmd = cmd.split(' ')
  33.         if (ncmd[0] == syntax+"logout"):
  34.             conn.close()
  35.             print("[client] executed logout. ending thread %d" % (tid))
  36.  
  37.         elif (ncmd[0] == syntax+"threads"):
  38.             conn.send("Total Threads [%d]" % (len(thread_id)))
  39.  
  40.     except Exception as e:
  41.         print(str(e))
  42.         print("[client] client ended session [thread id %s]" % (tid))
  43.         thread_start -= 1
  44.  
  45.         if(conn):
  46.             conn.close()
  47.  
  48. def server():
  49.     global thread_start
  50.     global thread_limit
  51.     global thread_id
  52.  
  53.     sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  54.     try:
  55.         sock.bind(("0.0.0.0", 701))
  56.     except socket.error:
  57.         print("[-] Socket Error: Could not bind address. Address already in use.")
  58.         sys.exit()
  59.  
  60.     sock.listen(0)
  61.  
  62.     try:
  63.         while True:
  64.             conn, addr = sock.accept()
  65.             print("[server] connection recieved from [%s:%s]" % (addr[0], addr[1]))
  66.             if (thread_limit == thread_start):
  67.                 print("[server] could not send client to shell [Maximum threads used]")
  68.  
  69.             elif (thread_limit != thread_start):
  70.                 print("[server] sent client to shell.")
  71.                 tid = get_thread_id()
  72.                 print("[server] thread started | ID %d" % (tid))
  73.                 thread_begin = threading.Thread(target=client, args=(conn, addr, tid,)).start()
  74.                 thread_start += 1
  75.  
  76.     except socket.error:
  77.         print("[-] You wont ever get this message. just saying.")
  78.  
  79. server()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement