1

ポートが利用可能かどうかを確認するためのPythonスクリプトを作成しようとしています。以下はコードの一部です(スクリプト全体ではありません)。

しかし、スクリプトを実行すると、ターミナルに出力が表示されません。ctrl+ cを押すと、スクリプトの単一の結果が得られます。もう一度ctrl + cを押すと、2番目の結果が得られます。スクリプトが完了すると、最終的に終了します...

#!/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'

私は何が間違っているのですか?

前もって感謝します!

4

1 に答える 1

1

デフォルトでは、ソケットはブロッキング モードで作成されます。

したがって、一般的には、呼び出すsettimeout()前に呼び出すconnect()か、タイムアウト パラメータを渡して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'
于 2012-10-25T13:14:28.070 に答える