我目前正在开发一个简单的 Python 程序,但由于某种原因,它无法正常工作。
完整程序的工作方式是它有一个包含 20 个端口的列表,然后循环遍历该列表,基本上在所选端口上 ping 主机。这是代码:
import socket
import sys
print '  +-====================================================-+'
print ' /                                                        \ '
print '|                       PyPortScanner                      |'
print '|                       by Ag3ntChr0m                      |'
print ' \                                                        /'
print '  +-====================================================-+'
print ''
try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error, msg:
    print 'Failed to create socket. Error code: ' + str(msg[0]) + 'Error message: ' + msg[1]
    sys.exit()
print 'Socket Created'
host = raw_input('Enter the desired host to scan: ')
port = [80, 443, 21, 22, 4567, 8080, 25, 3389, 23, 53, 1723, 110, 135, 445,
        139, 1863, 143, 8081, 10000, 1025]
portFail = []
print 'Scanning top 20 most often open ports ...'
try:
    remote_ip = socket.gethostbyname( host )
except socket.gaierror:
    #couldn't resolve host at port
    print 'Hostname could not be resolved. Program exiting'
    sys.exit()
print 'IP address of ' + host + ' is ' + remote_ip
print '+-===================================-+'
print '| Ports Scanned:----------------------|'
print '+-===================================-+'
print ''
#Connect to remote server
for i in range(0, 20):
    portScan = int(str(port[i]))    <----
    try:
        s.connect((remote_ip, portScan))
        print "\t" + str(portScan)
        s.close()
    except:
        portFail.append(portScan)
        err = True
raw_input('Press Enter to Continue...')
if err:
    print '+-=============================-+'
    print '| Failed Port Scan:-------------|'
    print '+-=============================-+'
    print ''
    size = len(portFail)
    for i in range(1, size):
        print "\t" + str(portFail[i])
当您运行程序时,它应该
- 将端口号(在箭头标记的行)加载到 s.socket 可以用来尝试连接的变量中。
- 然后它尝试在主机上打开一个套接字(基本上是 ping 它)然后关闭它。
- 如果它连接,它会在端口扫描下的屏幕上写入。
- 但是,如果它失败(并且最近失败了),它会打印在 Failed Port Scan 下。
当我运行该程序时,它会在 Ports Scanned 下打印列表中的第一个端口 (80),但其余端口则放置在 Failed Port Scan 下——即使我知道其中至少有一些是打开的。
我如何让这个程序 ping 比第一个成功更多的端口?