python_端口扫描小工具

端口扫描小工具

port_ip.py

#!usr/bin/env python 
#-*- coding:utf_8 -*-
import urllib
import socket
ip='192.168.16.136'
default_ports=[80,21,22,3389,1433]
def port_scan(ip,port):
    try:
        socket.setdefaulttimeout(3)
        s=socket.socket()
        s.connect((ip,port))
        print '[+] port:%d\t open'%port
        s.close()#关闭套接字
    except:
        pass
if __name__ == '__main__':
    for port in default_ports:
        port_scan(ip,port)

结果:

[+] port:80     open

port_ip_2.py

#!usr/bin/env python 
#-*- coding:utf_8 -*-
import urllib
import socket
ip='192.168.16.136'
default_ports=[80,21,22,3389,1433]
def port_scan(ip,port):
    try:
        socket.setdefaulttimeout(3)
        s=socket.socket()
        s.connect((ip,port))
        print '[+] port:%d\t open \t%s'%(port,socket.getservbyport(port))
        s.close()#关闭套接字
    except:
        pass
if __name__ == '__main__':
    for port in default_ports:
        port_scan(ip,port)

结果:

[+] port:80     open     http

####程序分析:

getservbyport(port)函数,获取对应端口所运行的的服务

map()函数的用法:

    map(f, iterable) 基本上等于:[f(x) for x in iterable]

map()函数案例

    >>> def add100(x):
    ...     return x + 100
    ... 
    >>> list1 = [11,22,33]
    >>> map(add100,list1)
    [101, 102, 103]

    >>> [add100(i) for i in list1]
    [101, 102, 103]

port_3.py

import urllib
import socket
ip='192.168.16.136'
default_ports=[80,21,22,3389,1433]
def port_scan(ip,port):
    try:
        socket.setdefaulttimeout(3)
        s=socket.socket()
        s.connect((ip,port))
        s.send('aaa\r\n')
        res=s.recv(40)
        print '[+] port:%d\t open \t%s'%(port,res)
        s.close()#关闭套接字
    except:
        pass
if __name__ == '__main__':
    map(port_scan,[ip]*len(default_ports),default_ports)

结果:

[+] port:80     open     <?xml version="1.0" encoding="iso-8859-1

发送数据,并且接收到一些数据,

port_4.py

#!usr/bin/env python 
#-*- coding:utf_8 -*-
import urllib

import socket,threading
ip='192.168.16.136'
default_ports=[21,22,80,1433,3306]

lock=threading.Semaphore(value=1)
def port_scan(ip,port):
    try:
        socket.setdefaulttimeout(3)
        s=socket.socket()
        s.connect((ip,port))
        s.send('dream9\r\n')
        res=s.recv(40)
        lock.acquire()
        print '[+] port:%d\topen\t%s' % (port,res)
        lock.release()
        s.close()
    except:
        pass

if __name__=='__main__':
    for port in default_ports:
        t=threading.Thread(target=port_scan,args=(ip,port))
        t.start()

####程序分析:

lock=threading.Semaphore(value=1)

信号机semaphore()每次有一个线程获取信号机,计数器为-1,如果为0,则其他线程就体制访问信号机,直到开始那个哪个线程释放信号机

lock.acquire(): 调用acquire()时-1

lock.release(): 释放Semaphore,将计数器+1

thread.exit()线程结束

详细请见:Hacking By Python—端口扫描1