-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathfind_printers.py
97 lines (81 loc) · 2.71 KB
/
find_printers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import os
import socket
import subprocess
import threading
import warnings
from epson_print_conf import EpsonPrinter
# suppress pysnmp warnings
warnings.filterwarnings("ignore", category=SyntaxWarning)
# common printer ports
PRINTER_PORTS = [9100, 515, 631]
class PrinterScanner:
def check_printer(self, ip, port):
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(1)
sock.connect((ip, port))
sock.close()
return True
except socket.error:
return False
def get_printer_name(self, ip):
printer = EpsonPrinter(hostname=ip)
try:
printer_info = printer.get_snmp_info("Model")
return printer_info["Model"]
except:
return None
def scan_ip(self, ip):
for port in PRINTER_PORTS:
if self.check_printer(ip, port):
try:
hostname = socket.gethostbyaddr(ip)[0]
except socket.herror:
hostname = "Unknown"
printer_name = self.get_printer_name(ip)
if printer_name:
return {
"ip": ip,
"hostname": hostname,
"name": printer_name
}
else:
return {
"ip": ip,
"hostname": hostname,
"name": "Unknown"
}
return None
def get_all_printers(self, ip_addr="", local=False):
if ip_addr:
result = self.scan_ip(ip_addr)
if result:
return [result]
local_device_ip_list = socket.gethostbyname_ex(socket.gethostname())[2]
if local:
return local_device_ip_list
printers = []
for local_device_ip in local_device_ip_list:
if ip_addr and not local_device_ip.startswith(ip_addr):
continue
base_ip = local_device_ip[:local_device_ip.rfind('.') + 1]
ips=[f"{base_ip}{i}" for i in range(1, 255)]
threads = []
def worker(ip):
result = self.scan_ip(ip)
if result:
printers.append(result)
for ip in ips:
thread = threading.Thread(target=worker, args=(ip,))
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
return printers
if __name__ == "__main__":
import sys
ip = ""
if len(sys.argv) > 1:
ip = sys.argv[1]
scanner = PrinterScanner()
print(scanner.get_all_printers(ip))