用于开放端口的Python简单网络扫描器

时间:2016-05-15 13:17:06

标签: python

我试图在不使用nmap的情况下在python中创建一个简单的端口扫描程序。

以下代码到目前为止:

    import socket,sys,optparse,netaddr


#INPUT
parser = optparse.OptionParser("usage: untitled1.py " "--ip <Network you want to scan, including mask in CIDR format> -P <target port>")
parser.add_option('--ip', dest='ip', type='string',  help='specify network to scan including /mask e.g 192.168.0.1/24')
parser.add_option('-P', dest='port', type='int',  help='specify target port')
(options, args) = parser.parse_args()
port = str(options.port)
ip = str(options.ip)


if (ip == None) | (port == None):
    print parser.usage
    print 'You must specify a target network,including subnet mask and port.'
    exit(0)

#CREATE A SOCKET
try:
  s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
except socket.error,err_msg:
  print 'Socket creation failed. Error code: '+ str(err_msg[0]) + ' Error mesage: ' + err_msg[1]
  sys.exit()

#PORT SCAN
targetlist = netaddr.IPNetwork(ip)
targetlist = list(targetlist)


for x in range (int(len(targetlist))):
    target_ip = targetlist[x]
    try:
      s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
      s.settimeout(2)
      result = s.connect(str(target_ip), int(port))
      if not result :
        print str(target_ip) + ' Port '+  str(port) + ' open!'
      s.close()
    except:
      print str(target_ip)+' Port '+ str(port) + ' closed!'


s.close()
print "Scanning finished"

它似乎不起作用,因为即使我确定特定端口是打开的,我尝试扫描的每个IP或网络都关闭了端口..

很可能我的错误在于端口扫描的定义方式,但我似乎无法将手指放在上面。

我处于初级水平,欢迎任何建议!

提前致谢!

0 个答案:

没有答案