端口扫描程序python脚本

时间:2015-01-10 07:19:00

标签: python

我是python的初学者,我在python中学习套接字对象。我在互联网上发现了一个脚本:

import socket

s = socket.socket()
socket.setdefaulttimeout(2)
try:
    s = s.connect(("IP_ADD", PORT_NUM))
    print "[+] connection successful"

except Exception, e:
    print "[+] Port closed"

我只是想问一下,这个脚本是否可以作为端口扫描程序使用?非常感谢!

2 个答案:

答案 0 :(得分:0)

只需更改您的代码,它就可以用作localhost的TCP端口扫描程序:

import socket

def scan_port(port_num, host):
  s = socket.socket()
  socket.setdefaulttimeout(2)
  try:
      s = s.connect((host, port_num))
      print port_num, "[+] connection successful"

  except Exception, e:
      print port_num, "[+] Port closed"

host = 'localhost'

for i in xrange(1024):
  scan_port(i, host)

但它只是一个玩具,如果你想扫描其他电脑的端口,就不能用它做真实的东西, 试试nmap

答案 1 :(得分:0)

这是我的端口扫描程序版本。我试着在评论中解释一切是如何运作的。

#-*-coding:utf8;-*-
#qpy:3
#qpy:console

import socket
import os

# This is used to set a default timeout on socket
# objects.
DEFAULT_TIMEOUT = 0.5

# This is used for checking if a call to socket.connect_ex
# was successful.
SUCCESS = 0

def check_port(*host_port, timeout=DEFAULT_TIMEOUT):
    ''' Try to connect to a specified host on a specified port.
    If the connection takes longer then the TIMEOUT we set we assume
    the host is down. If the connection is a success we can safely assume
    the host is up and listing on port x. If the connection fails for any
    other reason we assume the host is down and the port is closed.'''

    # Create and configure the socket.
    sock = socket.socket()
    sock.settimeout(timeout)

    # the SO_REUSEADDR flag tells the kernel to reuse a local 
    # socket in TIME_WAIT state, without waiting for its natural
    # timeout to expire.
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    # Like connect(address), but return an error indicator instead
    # of raising an exception for errors returned by the C-level connect() 
    # call (other problems, such as “host not found,” can still raise exceptions). 
    # The error indicator is 0 if the operation succeeded, otherwise the value of 
    # the errnovariable. This is useful to support, for example, asynchronous connects.
    connected = sock.connect_ex(host_port) is SUCCESS

    # Mark the socket closed. 
    # The underlying system resource (e.g. a file descriptor)
    # is also closed when all file objects from makefile() are closed.
    # Once that happens, all future operations on the socket object will fail. 
    # The remote end will receive no more data (after queued data is flushed).
    sock.close()

    # return True if port is open or False if port is closed.
    return connected


con = check_port('www.google.com', 83)
print(con)