通过子网迭代并运行portscan功能

时间:2018-04-16 20:49:13

标签: python networking

我正在尝试编写一个python程序,例如ping一个给定的网络(192.168.0.0/24)。然后将活动主机存储在一个数组中。从那个数组,我想用我写的函数端口扫描它们。但是,我不知道我做错了什么。

以下是不使用活动主机的脚本的精简版本,只是整个子网(它的想法相同):

#!/usr/bin/env python
import socket
import ipaddress

def portscan(host):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)    
    try:
        for port in range(75,85):  

            result = sock.connect_ex((host, port))
            if result == 0: #the error indictator returns 0 if the operation succeeds.
                print "port ",port," is open on ", host
            # else:
            #     print "port ",port," is closed"     
            sock.close()
            logging.debug(i)
    except:
        print "no connection on port",port, "from host",host        


def main():
    subnet = ipaddress.ip_network(u'192.168.0.0/29')
    for i in subnet:
        print i
        portscan(i)


if __name__ == "__main__":
    main()  

以上只会返回:

192.168.0.0
no connection on port 75 from host 192.168.0.0
192.168.0.1
no connection on port 75 from host 192.168.0.1
192.168.0.2
no connection on port 75 from host 192.168.0.2
192.168.0.3
no connection on port 75 from host 192.168.0.3
192.168.0.4
no connection on port 75 from host 192.168.0.4
192.168.0.5
no connection on port 75 from host 192.168.0.5
192.168.0.6
no connection on port 75 from host 192.168.0.6
192.168.0.7
no connection on port 75 from host 192.168.0.7
[Finished in 0.0s]

我还写了一个在一个特定主机上运行portscan的脚本,它运行得很好:

#!/usr/bin/env python
import socket
import sys

server = '192.168.0.1'
def portscanner():
    try:
        for port in range(1,445):  
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            result = sock.connect_ex((server, port))
            if result == 0: #the error indictator returns 0 if the operation succeeds.
                print "port",port," is open on",server
            # else:
            #     print "port ",port," is closed"     
            sock.close()


    except KeyboardInterrupt:
        print " CTRL+C Interruption. Exiting..." 
        sys.exit() 

portscanner()

硬编码的ip返回:

port 80  is open on 192.168.0.1
port 443  is open on 192.168.0.1
[Finished in 20.3s]

我已经写了很多不同的变体来让它发挥作用。但我一直都错了! 我也是Python的新手,所以要温柔!

TL; DR: 迭代一堆IP地址,并在每个IP地址上调用一​​个portscan函数。

1 个答案:

答案 0 :(得分:0)

try:
    for port in range(75,85): 

您的for循环位于try块内 - 只要一次连接尝试失败,它就会直接跳转到except子句,跳过循环中的所有其他端口。由于大多数系统都没有打开端口75,这将使“扫描”失败。

for循环移到try之外,就像在其他脚本中一样。