import socket, time, threading

devices = open("/tmp/devices.txt").read().strip().split("\n")
total = len(devices)
ok = []
lock = threading.Lock()
tested = [0]

def test_dev(line):
    parts = line.split(":")
    if len(parts) < 4: return
    ip, port, user, passwd = parts[0], int(parts[1]), parts[2], parts[3]
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.settimeout(4)
        s.connect((ip, port))
        time.sleep(0.3)
        data = s.recv(4096).decode(errors="ignore")
        if "login" in data.lower():
            s.send((user+"\r\n").encode())
            time.sleep(0.3)
            data = s.recv(4096).decode(errors="ignore")
        if "password" in data.lower():
            s.send((passwd+"\r\n").encode())
            time.sleep(0.8)
            data = s.recv(4096).decode(errors="ignore")
        try: s.recv(65536)
        except: pass
        s.send(b"echo VANTAOK\r\n")
        time.sleep(0.8)
        r = s.recv(4096).decode(errors="ignore")
        s.close()
        if "VANTAOK" in r:
            with lock:
                ok.append(line)
    except:
        pass
    with lock:
        tested[0] += 1

# Run 100 threads at a time
for i in range(0, total, 100):
    batch = devices[i:i+100]
    threads = []
    for line in batch:
        t = threading.Thread(target=test_dev, args=(line,))
        t.daemon = True
        threads.append(t)
        t.start()
    for t in threads:
        t.join(timeout=10)
    if (i+100) % 500 == 0 or i+100 >= total:
        print(f"{tested[0]}/{total} ok={len(ok)}")

with open("/tmp/_alive_devices.txt", "w") as f:
    f.write("\n".join(ok) + "\n")
with open("/tmp/_scan_result.txt", "w") as f:
    f.write(f"TOTAL={total} OK={len(ok)} FAIL={total-len(ok)}\n")

print(f"\nDONE: {len(ok)} alive devices out of {total}")
