(Python)尝试一次扫描一个IP地址的端口范围时出错

时间:2018-02-25 18:45:57

标签: python sockets ip port

我试图一次扫描用户指定的一个端口范围,直到第四个八位字节达到255.但是,我遇到一个错误,我的变量名为' count'虽然我将其定义为= 1,但未定义,因此程序将运行每个IP地址,如53.234.12.1,53.234.12.2,53.234.12.3等。

这是我试图在完成所有操作后在解释器中显示的内容: End Result

这是我的代码:

import socket

server = 'google.com'


startPort = int(input("Enter started port number to scan: "))
endPort = int(input("Enter ending port number to scan: "))
threeOctet = str(input("Enter the first three octets of an IP to scan: "))
countFullIP = threeOctet + "." + str(count)
count = 1

for countFullIP in range(0,256):
    for count in range (startPort,endPort):
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.connect((server,countFullIP))
            print('IP',countFullIP)
        except:
            print('IP is invalid')
        try:
             print('Port',count,'is open')
        except:
             print('Port',count,'is closed')

非常感谢任何帮助。谢谢!

1 个答案:

答案 0 :(得分:1)

替换两行

countFullIP = threeOctet + "." + str(count)
count = 1

count = 1
countFullIP = threeOctet + "." + str(count)

正如你所看到的,在分配之前引用了count。

根据评论中提到的其他要求更新代码。

import socket

server = 'google.com'

startPort = int(input("Enter started port number to scan: "))
endPort = int(input("Enter ending port number to scan: "))
threeOctet = str(input("Enter the first three octets of an IP to scan: "))

for count in range(0,256):
    countFullIP = threeOctet + "." + str(count)
    for count in range (startPort,endPort):
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.connect((server, countFullIP))
            print('IP',countFullIP)
        except:
            print('IP is invalid', countFullIP)
        try:
             print('Port',count,'is open')
        except:
             print('Port',count,'is closed')