Python port scanning program example

Source: Internet
Author: User
Tags socket

1, Python single threaded scan port, code as follows:

/tbody>
  code is as follows copy code


#!/usr/bin/env python
#coding: UTF8
Import socket
 
IP = ' Www.111cn.net
for port in range (1,1024,1):
    sk = Socket.socket (socket.af_inet, socket. SOCK_STREAM)
    sk.settimeout (2)
    print "Scanning port:%d"% port
  & nbsp Try:
        sk.connect ((ip,port))
         print ' Server%s port%d OK '% (ip,port)
    except Exception:
     ;    print ' Server%s port%d is not connected! '% (ip,port)
 
Sk.close ()

2, Python multi-process scan port, the code is as follows:

The code is as follows Copy Code


#!/usr/bin/env python
#coding: UTF8
Import socket
Import Sys
Import multiprocessing
Import time

def test (Port):
ip = ' www.chlinux.net '
Port = Int (port)
Print Port
SK = Socket.socket (socket.af_inet, socket. SOCK_STREAM)
Sk.settimeout (0.5)
Print "Scanning ports:%d"% port
Try
Sk.connect ((Ip,port))
Print "Server%s port%d OK"% (ip,port)
Except Exception:
Print "Server%s port%d is not connected!"% (Ip,port)
Sk.close ()

if __name__ = = ' __main__ ':
Pool = multiprocessing. Pool (PROCESSES=20)
For port in Xrange (1,65535):
Port = Int (port)
Pool.apply_async (test, Port,)
Pool.close ()
Pool.join ()
Print "sub-process (es) done."

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.