반응형
개발 중에 귀찮은 일들을 스크립트로 만들어두고 공유하려는 목적입니다.
만약 더 좋은 방법을 알고 계신다면면 댓글 달아주세요 !
script
import subprocess
from concurrent.futures import ThreadPoolExecutor
import argparse
import ipaddress
import os
import time
# Function to clear the console
def clear_console():
# Use 'cls' for Windows and 'clear' for Unix-like systems
os.system('cls' if os.name == 'nt' else 'clear')
# Function to ping an IP address
def ping_ip(ip):
result = subprocess.run(['ping', '-c', '1', '-W', '0.5', ip], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
if result.returncode == 0:
return ip
return None
# Function to ping multiple IPs and return the alive ones
def ping_ips(ips):
alive_ips = []
with ThreadPoolExecutor(max_workers=100) as executor:
results = executor.map(ping_ip, ips)
for ip in results:
if ip:
alive_ips.append(ip)
return alive_ips
# Function to format the output
def format_output(start_ip, end_ip, alive_ips):
clear_console() # Clear the console before printing
print(f"Scanning Range\n{start_ip} ~ {end_ip}")
if alive_ips:
print("\nAlive")
for ip in alive_ips:
print(f"- {ip}")
else:
print("\nAlive\n- None")
# Function to generate IP range from start to end IP
def generate_ip_range(start_ip, end_ip):
start = ipaddress.IPv4Address(start_ip)
end = ipaddress.IPv4Address(end_ip)
return [str(ipaddress.IPv4Address(ip)) for ip in range(int(start), int(end) + 1)]
# Main function
def main():
parser = argparse.ArgumentParser(description="Ping IP addresses within a specified range.")
parser.add_argument('--start', required=True, help="Start IP address")
parser.add_argument('--end', required=True, help="End IP address")
parser.add_argument('-r', '--repeat', action='store_true', help="Repeat indefinitely until stopped")
args = parser.parse_args()
ips = generate_ip_range(args.start, args.end)
try:
if args.repeat:
# Infinite loop until stopped manually (e.g., with Ctrl+C)
while True:
alive_ips = ping_ips(ips)
format_output(args.start, args.end, alive_ips)
time.sleep(1) # Optional: Add a short delay between repetitions if needed
else:
# Single execution
alive_ips = ping_ips(ips)
format_output(args.start, args.end, alive_ips)
except KeyboardInterrupt:
print("\nExecution stopped by user. Exiting gracefully...")
if __name__ == "__main__":
main()
example (w/o repeat)
- start : 시작 IP
- end : 끝 IP
- repeat : 반복 여부 (마지막에 --repeat을 추가)
생각해보니 이 스크립트는 IP의 가장 마지막 자리만 변경해가면서 scan하고 있네요.
따라서 처음의 AAA.BBB.CCC 는 동일해야 하고, 만약 이 AAA,BBB,CCC가 다른 경우에 대해서는 고려되어있지 않습니다.
python3 scan.py --start 192.168.13.100 --end 192.168.13.150
Scanning Range
192.168.13.100 ~ 192.168.13.255
Alive
- 192.168.13.101
- 192.168.13.105
- 192.168.13.126
스크립트 작성 배경
여러 디바이스들의 상호작용이 필요한 분산 시스템을 개발하는 경우,
각 디바이스의 네트워크 상태가 정상인지 확인하는 것은 아주 중요한 일이다.
한쪽의 시스템을 완벽히 구성하고 전부 정상적으로 동작중이더라도,
어느 한쪽의 디바이스가 정상적으로 동작하지 못하면
테스트 결과가 이상하던지 아니면 테스트 자체가 불가능할 수도 있다.
최근 진행 중인 프로젝트에서는 어떤 SoC를 쓰냐, 시스템을 어떻게 구성하느냐에 따라 디바이스의 네트워크가 불능에 빠지는 경우를 꽤 자주 보게 되기도 하는데, 이로 인해 시간을 낭비하게 되는 경우가 많았다.
아직은 이 프로젝트의 진척이나 시스템의 성숙도가 낮아서 번거롭지만 이러한 fault들을 직접 모니터링해야 하는 필요성이 생겼고 간단하게 스크립트를 만들어 사용하게 되었다.
반응형