一端口扫描器,同步互斥

图片 40
ca88会员登录中心

手续:1、新建复信号量对象,设置非能量信号量数量
二、线程推行措施中,要是能够赢得连续信号量,则实行,频域信号量为0不能够赢得

经过补充进度间的随机信号时限信号量进程的一块互斥伊夫nt事件Lock 锁

内容:端口扫描器—脚本调用参数、拾贰线程扫描、使用Nmap端口扫描代码

图片 1图片 2

进程补充

环境:python+kali,靶机:win2003
分为五步编写
###############一、脚本调用的参数

 1 import  threading,time
 2 
 3 class  MyThread(threading.Thread):
 4     def  run(self):
 5         if  sema.acquire():
 6             print(self.name)
 7             time.sleep(0.3)
 8             sema.release()
 9 
10 if __name__ == '__main__':
11     sema = threading.BoundedSemaphore(5)  # sema=threading.Semaphore(5)
12     thrs = []
13     for i in range(100):
14         thrs.append(MyThread())
15     for t in thrs:
16         t.start()

经过间的实信号

非时域信号是唯一的异步通讯方式

三个历程向另贰个历程发送1个非确定性信号来传递某种新闻,接受者依照传递的音讯来做相应的事

$ kill -l翻看系统时域信号表达

$ kill -9 pid号对经过发送数字信号

信号名称 说明
1) SIGHUP 连接断开
2) SIGINT ctrl+c
3) SIGQUIT ctrl+\
20) SIGTSTP ctrl+z
9) SIGKILL 终止进程
19) SIGSTOP 暂停进程
26) SIGVTALRM 时钟信号
17) SIGCHLD 子进程退出时给父进程发的信号

在Python中import signal能够收获时域信号

  • os.kill

    • 效用:发送非确定性信号

    • 参数

      • pid:要发送时域信号的PID号
      • sig :确定性信号名称

图片 3图片 4

   import osimport signalos.kill(12345,signal.SIGKILL) #杀死进程

View Code

  • signal.alarm

    私家领会:把发送功率信号的新闻告诉系统基本,应用层程序继续运维,时间到现在选取内核告知应用层程序实行拍卖

  • 效果:非阻塞函数,向自个儿进度发送一个石英钟非能量信号
  • 参数:time->整型时间秒
  • 图片 5图片 6

         import signal  import time  signal.alarm#3秒后向自身发送一个时钟信号  while True:      time.sleep(1)      print("等待时钟信号")        '''打印结果  等待时钟信号  等待时钟信号  闹钟  '''        
    

    View
    Code图片 7图片 8

         signal.alarm#3秒后向自身发送一个时钟信号  time.sleep(2)  signal.alarm#进程只有一个时钟信号,第二个会覆盖上面的时钟信号  while True:      time.sleep(1)      print("等待时钟信号")        '''打印结果  等待时钟信号  等待时钟信号  等待时钟信号  等待时钟信号  闹钟  '''
    

    View Code

  • signal.pause()

  • 成效:阻塞进度,然后等待随机信号
  • signal.signal(signum, handler)

  • 功效:管理数字信号
  • 参数

  • signum:要拍卖的功率信号

    • handler:非确定性信号的拍卖方法

      • SIG_DFL意味着使用默许方法处理

      • SIG_IGN代表忽略那么些能量信号

      • function表示传入贰个函数,用钦赐的函数管理

        • def function(sig, frame)

          sig:捕获到的功率信号

          frame:时域信号对象

图片 9View图片 10图片 11

  import signal  from time import sleep    signal.alarm  # 5秒后向自身发送一个时钟信号  # 使用信号的默认方法处理  # signal.signal(signal.SIGALRM,signal.SIG_DFL)      # 忽略时钟信号  # signal.signal(signal.SIGALRM,signal.SIG_IGN)  # 忽略Ctrl+c信号  # signal.signal(signal.SIGINT,signal.SIG_IGN)  while True:      sleep(2)      print("等待时钟...")

View
Code图片 12图片 13

  # 使用自定义函数处理信号  import signal  from time import sleep    def fun1(sig, frame):      if sig == signal.SIGALRM :          print("接收到时钟信号")      elif sig == signal.SIGINT :          print("ctrl+c就不结束")    signal.alarm  # 5秒后向自身发送一个时钟信号  # 使用自定义函数处理信号  # 处理时钟信号  signal.signal(signal.SIGALRM,fun1)      # 处理ctrl+c信号  signal.signal(signal.SIGINT,fun1)    while True:      print("等待")      sleep(2)        '''打印结果  等待  等待  等待  接收到时钟信号  等待  ...  '''   

View Code

图片 14图片 15

View Code

信号量

原理:给定二个数据对七个经过可知,且四个进度都能够操作,进度能够对数码多少的剖断实行各自的作为

from multiprocessing import Semaphore

  • sem = Semaphore

    • 效率:成立频限信号量
    • 参数:信号量的起首值
    • 再次来到值:实信号量的目的
  • sem.get_value():获取功率信号量的值

  • sem.acquire():将时限信号量 -一,当信号为0时会卡住

  • sem.release():将信号量 +一

图片 16图片 17

from multiprocessing import Semaphore, Process# 创建信号量对象sem = Semaphoredef fun():    print("进程%d等待信号量"%os.getpid    # 消耗一个信号量    sem.acquire()    print("进程%d消耗信号量"%os.getpid    # 添加一个信号量    sem.release()    print("进程%d添加信号量"%os.getpidjobs = []for i in range(4):    p = Process(target = 4)    jobs.append    p.start()for i in jobs:    i.join()print(sem.get_value

View Code

import optparse
parser = optparse.OptionParser('usage %prog -H <target host> -p <target port>')
parser.add_option('-H', dest='tgtHost', type='string', help='specify target host')
parser.add_option('-p', dest='tgtPort', type='int', help='specify target port')
(options, args) = parser.parse_args()
tgtHost = options.tgtHost
tgtPort = options.tgtPort
if tgtHost == None | tgtPort == None:
    print(parser.usage)
    exit(0)

 

经过的同步互斥

临界财富:五个经过或许线程都能操作的共享能源

临界区:操作临界区财富的代码段

同步:同步是一种同盟关系,为成功某些职责,多进度恐怕10二线程之间形成的1种和谐关系

互斥:互斥是一种制裁关系,

View Code

 

Event事件

from multiprocessing import Event

  • e = Event():创制1个事件目的
  • e.wait([timeout]):设置事件阻塞
  • e.set():事件设置,当事件棉被服装置后e.wait()不再阻塞,等于释放能源区
  • e.clear():清除装置,当事件被设置e.clear()后,e.wait()又会堵塞,阻塞资源区
  • e.is_set():事件情形决断,剖断事件是或不是处在棉被服装置的景况

图片 18图片 19

from multiprocessing import Event# 创建事件对象e = Event()# 查看print(e.is_set        # Falsee.set()print(e.is_set        # Truee.wait(3)print(e.is_set        # Truee.clear()print(e.is_set        # False

View
Code图片 20图片 21

from multiprocessing import Event,Processfrom time import sleepdef wait_event1():    print("1想操作临界区资源")    e.wait()    print("1开始操作临界区资源",e.is_set    with open("file") as f:        printdef wait_event2():    print("2也想操作临界区资源")    # 超时3秒检测    e.wait(3)    # 判断是否被设置    if e.is_set():        print("2开始操作临界区资源",e.is_set        with open("file") as f:            print    else:        print("2不能操作")       # 创建事件对象e = Event()p1 = Process(target = wait_event1)p2 = Process(target = wait_event2)p1.start()p2.start()print("主进程操作")with open("file",'w') as f:    f.write("HELLO WORD")# 延迟4秒释放临界区sleep(4)# 释放临界区资源e.set()print("释放临界区")p1.join()p2.join()

View Code

################2、生成connScan和portScan函数

例子:

Lock 锁

from multiprocessing import Lock

  • lock = Lock():创造二个锁对象
  • lock.acquire():上锁,要是已经是上锁状态,调用此函数会阻塞
  • lock.release():解锁

图片 22图片 23

from multiprocessing import Lock,Processimport sysdef writer1():    # 上锁    lock.acquire()    for i in range(20):        sys.stdout.write("writer1111\n")    # 解锁    lock.release() def writer2():    # 上锁    lock.acquire()    for i in range(20):        sys.stdout.write("writer2222\n")    # 解锁    lock.release()lock = Lock()w1 = Process(target = writer1)w2 = Process(target = writer2)w1.start()w2.start()w1.join()w2.join()

View Code

第一种方法

使用with话语上锁,with语句施行完结后会自动解

with lock:    .....    .....    

图片 24图片 25

### 强行改的数字信号量

from socket import *

def connScan(tgtHost, tgtPort):
    try:
        connSkt = socket(AF_INET, SOCK_STREAM)
        connSkt.connect((tgtHost, tgtPort))
        print('[+] %d/tcp open' % tgtPort)
        connSkt.close()
    except:
        print('[-] %d/tcp close' % tgtPort)

def portScan(tgtHost, tgtPorts):
    try:
        tgtIP = gethostbyname(tgtHost)
    except:
        print('[-] Cannot resolve %s:Unknown host' % tgtHost)
        return
    try:
        tgtName = gethostbyaddr(tgtIP)
        print('[+] Scan Results for: ' + tgtName)
    except:
        print('[+] Scan Results for: ' + tgtIP)
    setdefaulttimeout(1)
    for tgtPort in tgtPorts:
        print('Scanning port:' + tgtPort)
        connScan(tgtHost, int(tgtPort))

图片 26图片 27

View Code

 1 import threading
 2 import time
 3 class Tickets:
 4     def __init__(self):
 5     self.ticket = 100
 6 
 7     def sell_ticket(self):
 8         while self.ticket > 0:
 9             if loc.acquire():
10                 print('卖出',self.ticket,'票',threading.current_thread())
11                 self.ticket -= 1
12                 loc.release()
13             time.sleep(0.0001)
14 
15 if __name__ == '__main__':
16     ticket = Tickets()
17     t1 = threading.Thread(target=ticket.sell_ticket)
18     t2 = threading.Thread(target=ticket.sell_ticket)
19     t3 = threading.Thread(target=ticket.sell_ticket)
20     loc = threading.Semaphore(1)
21     t1.start()
22     t2.start()
23     t3.start()

#################3、抓取应用的Banner
在connScan函数里面增添新扩展代码,找到开放的端口后,发送三个字符串等待响应

View Code

图片 28图片 29

##########38里边多生产多消费功率信号量达成

 1 import optparse
 2 from socket import *
 3 
 4 def connScan(tgtHost, tgtPort):
 5     try:
 6         connSkt = socket(AF_INET, SOCK_STREAM)
 7         connSkt.connect((tgtHost, tgtPort))
 8         connSkt.send('ViolentPython\r\n')
 9         results = connSkt.recv(100)
10         print('[+] %d/tcp open' % tgtPort)
11         #print('[+] retult' , str(results))
12         connSkt.close()
13     except:
14         print('[-] %d/tcp close' % tgtPort)
15 
16 def portScan(tgtHost, tgtPorts):
17     try:
18         tgtIP = gethostbyname(tgtHost)
19     except:
20         print('[-] Cannot resolve %s:Unknown host' % tgtHost)
21         return
22     try:
23         tgtName = gethostbyaddr(tgtIP)
24         print('[+] Scan Results for: ' + tgtName)
25     except:
26         print('[+] Scan Results for: ' + tgtIP)
27     setdefaulttimeout(1)
28     for tgtPort in tgtPorts:
29         print('Scanning port:' + tgtPort)
30         connScan(tgtHost, int(tgtPort))
31         
32 def main():
33     parser = optparse.OptionParser('usage %prog -H <target host> -p <target port>')
34     parser.add_option('-H', dest='tgtHost', type='string', help='specify target host')
35     parser.add_option('-p', dest='tgtPort', type='string', help='specify target port')
36     (options, args) = parser.parse_args()
37     tgtHost = options.tgtHost
38     tgtPort = options.tgtPort
39     tgtPorts = str(tgtPort).split(',')
40     if tgtHost == None or tgtPort== None:
41         print(parser.usage)
42         print('[-] you must specify a target host and port[s]')
43         exit(0)
44     portScan(tgtHost,tgtPorts)    
45 
46 if __name__ == '__main__':
47     main()

图片 30图片 31

View Code

 1 import time
 2 import threading
 3 
 4 class Res:
 5     def __init__(self):
 6         self.flag = False
 7         self.count = 0
 8         self.product = ''
 9 
10     def set(self,name):
11         lock_con.acquire()
12         while self.flag:
13             lock_con.wait()
14         time.sleep(0.00001)
15         self.count += 1
16         self.product = ''.join([name,'**',str(self.count)])
17         self.message = ''.join([self.product,'__生产者__',str(threading.current_thread())])
18         print(self.message)
19         self.flag = True
20         lock_con.notifyAll()
21         lock_con.release()
22 
23     def get_product(self):
24         lock_con.acquire()
25         time.sleep(0.00001)
26         while not self.flag:
27             lock_con.wait()
28         self.message = ''.join([self.product,'__消费者__',str(threading.current_thread())])
29         print(self.message)
30         self.flag = False
31         lock_con.notifyAll()
32         lock_con.release()
33 
34 class Producer(threading.Thread):
35     def __init__(self,r):
36         threading.Thread.__init__(self)
37         self.r = r
38 
39     def run(self):
40         for i in range(100):
41             self.r.set('大白兔奶糖')
42 
43 class Consumer(threading.Thread):
44     def __init__(self,r):
45         threading.Thread.__init__(self)
46         self.r = r
47 
48     def run(self):
49         for i in range(100):
50             self.r.get_product()
51 
52 if __name__ == '__main__':
53     lock_con = threading.Condition()
54     r = Res()
55     l = []
56     for i in range(5):
57         l.append(Consumer(r))
58     for i in range(5):
59         l.append(Producer(r))
60     for a in l:
61         a.start()

在此地一度足以因此调用脚本的款式进行
在终端实行的吩咐:root@HuaHong:~/python_hacker/chap2/端口扫描器#
python port_scanner.py -H 192.168.10.142 -p 80,21
图片 32

View Code

要专注的正是逗号不即使华语,许多个人会小心,当然也有人未有理会
照旧在python代码里面和这里保持壹致,作者觉着用英文的逗号就行了。

 

####################肆、线程扫描

图片 33图片 34

 1 import optparse
 2 
 3 from socket import *
 4 from threading import Thread,Semaphore
 5 
 6 screenLock = Semaphore(1)
 7 def connScan(tgtHost, tgtPort):
 8     try:
 9         connSkt = socket(AF_INET, SOCK_STREAM)
10         connSkt.connect((tgtHost, tgtPort))
11         connSkt.send('ViolentPython\r\n')
12         results = connSkt.recv(100)
13         screenLock.acquire()
14         print('[+] %d/tcp open' % tgtPort)
15         print('[+] retult' , str(results))
16         connSkt.close()
17     except:
18         screenLock.acquire()
19         print('[-] %d/tcp close' % tgtPort)
20     finally:
21         screenLock.release()
22         connSkt.close()
23 
24 def portScan(tgtHost, tgtPorts):
25     try:
26         tgtIP = gethostbyname(tgtHost)
27     except:
28         print('[-] Cannot resolve %s:Unknown host' % tgtHost)
29         return
30     try:
31         tgtName = gethostbyaddr(tgtIP)
32         print('[+] Scan Results for: ' + tgtName)
33     except:
34         print('[+] Scan Results for: ' + tgtIP)
35     setdefaulttimeout(1)
36     for tgtPort in tgtPorts:
37         # print('Scanning port:' + tgtPort)
38         # connScan(tgtHost, int(tgtPort))
39         t = Thread(target=connScan, args=(tgtHost,int(tgtPort)))
40         t.start()
41         
42 def main():
43     parser = optparse.OptionParser('usage %prog -H <target host> -p <target port>')
44     parser.add_option('-H', dest='tgtHost', type='string', help='specify target host')
45     parser.add_option('-p', dest='tgtPort', type='string', help='specify target port')
46     (options, args) = parser.parse_args()
47     tgtHost = options.tgtHost
48     tgtPort = options.tgtPort
49     tgtPorts = str(tgtPort).split(',')
50     if tgtHost == None or tgtPorts[0] == None:
51         print(parser.usage)
52         print('[-] you must specify a target host and port[s]')
53         exit(0)
54     portScan(tgtHost,tgtPorts)    
55 
56 if __name__ == '__main__':
57     main()

View Code

此处运用拾二线程扫描提升了速率,并且加入了非确定性信号量。
在选拔时限信号量前要导入
测试结果
图片 35

 

########################五应用Nmap端口扫描代码
在使用Nmap从前要设置python-nmap
图片 36

自家计算机kali暗中认可就有
图片 37

图片 38图片 39

 1 # __author: _nbloser
 2 # date: 18-3-16
 3 
 4 import nmap
 5 import optparse
 6 
 7 
 8 def nmapScan(tgtHost, tgtPort):
 9     nmScan = nmap.PortScanner()
10     nmScan.scan(tgtHost, tgtPort)
11     state = nmScan[tgtHost]['tcp'][int(tgtPort)]['state']
12     print("[*]" + tgtHost + " tcp/" + tgtPort + ' ' + state)
13 
14 def main():
15     parser = optparse.OptionParser('usage %prog -H <target host> -p <target port>')
16     parser.add_option('-H', dest='tgtHost', type='string', help='specify target host')
17     parser.add_option('-p', dest='tgtPort', type='string', help='specify target port')
18     (options, args) = parser.parse_args()
19     tgtHost = options.tgtHost
20     tgtPort = options.tgtPort
21     tgtPorts = str(tgtPort).split(',')
22     if tgtHost == None or tgtPorts[0] == None:
23         print(parser.usage)
24         print('[-] you must specify a target host and port[s]')
25         exit(0)
26     for tgtPort in tgtPorts:
27         nmapScan(tgtHost, tgtPort)
28 
29 
30 if __name__ == '__main__':
31     main()

View Code

 实践结果,实施会相当的慢点

图片 40

nmap调用为重代码:

def nmapScan(tgtHost, tgtPort):
    nmScan = nmap.PortScanner()
    nmScan.scan(tgtHost, tgtPort)
    state = nmScan[tgtHost]['tcp'][int(tgtPort)]['state']
    print("[*]" + tgtHost + " tcp/" + tgtPort + ' ' + state)

手续:一)获取相应扫描对象
    2)扫描
    三)获取结果

 

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图