2012-10-25 4 views
1

포트가 사용 가능한지 확인하기 위해 Python 스크립트를 만들려고합니다. 아래는 전체 스크립트가 아닌 코드의 일부입니다.Python : 결과를 얻으려면 Ctrl + C를 누르십시오.

그러나 스크립트를 실행하면 터미널에 출력이 표시되지 않고 Ctrl + C를 누르면 스크립트의 단일 결과가 표시되고 Ctrl + C를 누르면 두 번째 결과가 나타납니다. 스크립트가 끝나면 마침내 종료됩니다 ...

#!/usr/bin/python 

import re 
import socket 
from itertools import islice 

resultslocation = '/tmp/' 
f2name = 'positives.txt' 
f3name = 'ip_addresses.txt' 
f4name = 'common_ports.txt' 

#Trim down the positive results to only the IP addresses and scan them with the given ports in the common_ports.txt file 

with open(resultslocation + f2name, 'r') as f2, open(resultslocation + f3name, 'w') as f3: 
    hits = f2.read() 
    list = re.findall(r'name = (.+).', hits) 
    for items in list: 
     ip_addresses = socket.gethostbyname(items) 
     with open(resultslocation + f4name, 'r') as f4: 
      for items in f4: 
       ports = int(items) 
       s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
       try: 
        s.connect((ip_addresses, ports)) 
        s.shutdown(2) 
        print 'port', ports, 'on', ip_addresses, 'is open' 
       except: 
        print 'port', ports, 'on', ip_addresses, 'is closed' 

내가 뭘 잘못하고 있니?

미리 감사드립니다.

+1

결과는 무엇입니까? - 나는's.connect'가 당신이 무언가에 연결할 때까지 실행을 차단하지만, 연결에 실패했기 때문에 거기서 기다리고 있다고 생각합니다. 'ctrl-c'를 누르면 (** bare! **) 예외 처리기에서 처리되는'KeyboardInterrupt' 예외가 발생합니다. – mgilson

+1

[getdefaulttimeout] (http://docs.python.org/library/socket.html#socket.getdefaulttimeout) 및 [setdefaulttimeout] (http://docs.python.org/library/socket)을 살펴볼 수 있습니다. html # socket.setdefaulttimeout) 그리고 마지막으로 [create_connection] (http://docs.python.org/library/socket.html#socket.create_connection) – mgilson

+0

다른 몇 가지. 변수 이름으로'list'를 사용하지 마십시오. 내장 함수이므로 코드가 혼란스럽고 버그가 발생할 수 있습니다. 또한 다른 데이터 (이 경우 항목)를 나타 내기 위해 내부 및 외부 루프에서 동일한 변수 이름을 사용하는 것이 가장 좋은 아이디어는 아닙니다. 마지막으로,'ports'와'items'를 복수화하는 것은 오해의 소지가 있습니다. 실제로 변수가 여러 값을 표현하는 것처럼'ports = int (items)'는 예외를 발생시킵니다. –

답변

1

기본적으로 소켓은 차단 모드로 만들어집니다.

일반적으로 connect()을 호출하기 전에 settimeout()을 호출하거나 시간 초과 매개 변수를 create_connection()으로 전달하고 연결 대신이를 사용하는 것이 좋습니다. 코드에서 이미 예외를 캡처하므로 첫 번째 옵션은 구현하기 쉽습니다.

with open(resultslocation + f2name, 'r') as f2, open(resultslocation + f3name, 'w') as f3: 
    hits = f2.read() 
    list = re.findall(r'name = (.+).', hits) 
    for items in list: 
     ip_addresses = socket.gethostbyname(items) 
     with open(resultslocation + f4name, 'r') as f4: 
      for items in f4: 
       ports = int(items) 
       s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
       s.settimeout(1.0) # Set a timeout (value in seconds). 
       try: 
        s.connect((ip_addresses, ports)) 
        s.shutdown(2) 
        print 'port', ports, 'on', ip_addresses, 'is open' 
       except: 
        # This will alse catch the timeout exception. 
        print 'port', ports, 'on', ip_addresses, 'is closed' 
+0

빠른 답장을 보내 주셔서 감사합니다! 's.settimeout (1.0) # 타임 아웃을 설정하십시오 (초 단위의 값)'해결책입니다! –