from socket import * from threading import Thread import re import time global ThreadCnt ThreadCnt = 0 PortList = {20:'FTP', 21:'FTP', 22:'SSH', 23:'Telnet', 24:'mail', 25:'SMTP', 80:'HTTP', 443:'HTTPS', 3306:'MySQL'} def ConnScan(Target_Host, Target_Port): # sT try: connskt = socket(AF_INET, SOCK_STREAM) connskt.connect((Target_Host, Target_Port)) connskt.send('hello') result = connskt.recv(1024) file_result = open('result.txt','a') file_result.write('[' + PortList[Target_Port] + ']' + '[' + str(Target_Port) + ']' + Target_Host + '\n') file_result.close() connskt.close() except: pass global ThreadCnt ThreadCnt -= 1 def PortScan(Target_Host, Target_Port): # T port global ThreadCnt for ip in Target_Host: print('Scanning : ' + ip) print(str(ThreadCnt)) for port in Target_Port: while True : if ThreadCnt > 500 : continue t = Thread (target=ConnScan, args=(ip, port)) ThreadCnt +=1 t.start() break def main(): file = open("iplist.txt", "r") Target_Host = [] Target_Port = PortList.keys() cnt = 0 for text in file.readlines(): text = text.rstrip() regex = re.findall(r'(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})$', text) if regex is not None and regex not in Target_Host: cnt += 1 Target_Host.append("".join(regex)) print(Target_Host) PortScan(Target_Host, Target_Port) if __name__ == '__main__': main() from socket import * from threading import Thread, Lock import re import time global ThreadCnt ThreadCnt = 0 PortList = {20: 'FTP', 21: 'FTP', 22: 'SSH', 23: 'Telnet', 24: 'mail', 25: 'SMTP', 80: 'HTTP', 443: 'HTTPS', 3306: 'MySQL'} file_lock = Lock() def ConnScan(Target_Host, Target_Port): # sT global ThreadCnt try: connskt = socket(AF_INET, SOCK_STREAM) connskt.settimeout(2) # 타임아웃 설정 추가 connskt.connect((Target_Host, Target_Port)) # 파이썬 3에 맞게 bytes로 변환 connskt.send(b'hello') result = connskt.recv(1024) # 파일 쓰기 동기화 (Lock 사용) with file_lock: file_result = open('result.txt', 'a', encoding='utf-8') file_result.write('[' + PortList[Target_Port] + ']' + '[' + str(Target_Port) + ']' + Target_Host + '\n') file_result.close() connskt.close() except: pass # 스레드 카운트 감소는 안전하게 처리 with file_lock: ThreadCnt -= 1 def PortScan(Target_Host, Target_Port): # T port global ThreadCnt for ip in Target_Host: print('Scanning : ' + ip) print(str(ThreadCnt)) for port in Target_Port: while True: if ThreadCnt > 500: time.sleep(0.01) # CPU 100% 점유 방지 continue # t.start()의 적합한 위치 (루프 내부, 스레드 객체 생성 직후) t = Thread(target=ConnScan, args=(ip, port)) with file_lock: ThreadCnt += 1 t.start() break def main(): file = open("iplist.txt", "r", encoding='utf-8') Target_Host = [] Target_Port = PortList.keys() for text in file.readlines(): text = text.rstrip() regex = re.findall(r'(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})$', text) if regex: # re.findall은 리스트를 반환하므로 첫 번째 요소를 가져오거나 문자열 결합 처리 ip_str = regex[0] if isinstance(regex, list) else "".join(regex) if ip_str not in Target_Host: Target_Host.append(ip_str) print(Target_Host) PortScan(Target_Host, Target_Port) if __name__ == '__main__': main() from concurrent.futures import ThreadPoolExecutor, as_completed import socket import re PortList = {20: 'FTP', 21: 'FTP', 22: 'SSH', 23: 'Telnet', 24: 'mail', 25: 'SMTP', 80: 'HTTP', 443: 'HTTPS', 3306: 'MySQL'} def ConnScan(Target_Host, Target_Port): # sT try: with socket.create_connection((Target_Host, Target_Port), timeout=2): service = PortList[Target_Port] return '[' + service + ']' + '[' + str(Target_Port) + ']' + Target_Host except OSError: return None def PortScan(Target_Host, Target_Port, max_workers=100): # T port Target_Port = list(Target_Port) futures = [] open_count = 0 for ip in Target_Host: print('Scanning : ' + ip) with ThreadPoolExecutor(max_workers=max_workers) as executor: for ip in Target_Host: for port in Target_Port: futures.append(executor.submit(ConnScan, ip, port)) for future in as_completed(futures): scan_result = future.result() if scan_result: open_count += 1 print(scan_result) with open('result.txt', 'a', encoding='utf-8') as file_result: file_result.write(scan_result + '\n') if open_count == 0: print('No open ports found.') def main(): open('result.txt', 'w', encoding='utf-8').close() Target_Host = [] Target_Port = PortList.keys() with open("iplist.txt", "r", encoding='utf-8') as file: for text in file.readlines(): text = text.rstrip() regex = re.findall(r'(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})$', text) if regex and regex[0] not in Target_Host: Target_Host.append(regex[0]) print(Target_Host) PortScan(Target_Host, Target_Port) if __name__ == '__main__': main() import socket import ipaddress import re port_regex = re.compile("([0-9]+){1,5}-([0-9]+){1,5}") ip_regex1 = re.compile("^\d") ip_regex2 = re.compile("^www\.") while True: ip_addr_input = input("IP주소 또는 도메인 주소를 입력하세요(ex: 127.0.0.1 or www.naver.com) :") try: ip_regex1_valid = ip_regex1.search(ip_addr_input.replace(" ","")) ip_regex2_valid = ip_regex2.search(ip_addr_input.replace(" ","")) if ip_regex1_valid: ip_addr = ipaddress.ip_address(ip_addr_input) break elif ip_regex2_valid: ip_addr = ip_addr_input break except: print("잘못된 주소 형식입니다.") while True: port_min = 0 port_max = 65535 port_range = input("포트범위를 정해주세요(ex:0-65535) :") port_range_valid = port_regex.search(port_range.replace(" ","")) if port_range_valid: port_min = int(port_range_valid.group(1)) port_max = int(port_range_valid.group(2)) break valid_ports = [] for port in range(port_min, port_max + 1): try: with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.settimeout(0.5) # 타임아웃이 뜨는 경우 socket을 다시 만든다. s.connect((str(ip_addr), port)) valid_ports.append(port) except: print("port",port,"not open") pass for port in valid_ports: print(f"{ip_addr_input} 주소에 {port}가 연결되었습니다")