[Python black hat] 3. Programming IP and port scanner, multi thread C segment scanner

Eastmount 2020-11-13 00:00:57
python black hat programming ip


Python Black hat's third article will share the basics of network scanning , Programming to realize IP And port scanner 、 Implement multithreading C Segment scanner . This paper refers to 《Python stunt 》 Books and i spring and autumn ADO Teacher's course content , I really recommend you to study here ichunqiu Course , At the same time, it is also explained with the author's programming experience . I hope this basic article can help you , I hope you can improve your safety awareness , Welcome to discuss .

Na Zhang AI Safety home in 2020 year 8 month 18 Open daily , Will focus on Python And security technology , Mainly share Web penetration 、 System security 、CVE Reappear 、 Threat Intelligence Analysis 、 Artificial intelligence 、 Big data analysis 、 Malicious code detection and other articles . I really want to share what I have learned and done in the past ten years , Make progress with everyone .

Statement : I firmly oppose the use of teaching methods to carry out malicious attacks , All wrong behavior will be severely punished , Green network needs our common maintenance , We also recommend that you understand the principle behind the technology , Better security protection . Although the author is a safe little white , But it will ensure that every article will be carefully written , I hope these basic articles will help you , On the safe road together .

List of articles

  • One .Python Multithreading
  • Two . Programming to realize ping scanning
  • 3、 ... and . testing IP Survival address
  • Four . Programming port scanner
  • 5、 ... and . Multithreading +Queue Realization C Segment scan


One .Python Multithreading

1. Processes and threads

process : It's an execution of the program , Each process has its own address space 、 Memory 、 Data stack and other auxiliary data to record the running track .
Threads : All threads run in the same process , Share the same running environment . The thread has started 、 Sequence execution and completion of three parts .

Due to the low efficiency of single thread , Multi thread programming is often introduced into the program . The core of a computer is CPU, It does all the computing , It's like a factory , Running all the time . Suppose the power of the factory is limited , It can only be used in one workshop at a time . in other words , When a workshop starts , All other workshops have to be shut down . The meaning behind it is , Single CPU You can only run one task at a time .

The process is like the workshop of a factory , It represents CPU The single task that can be handled . Any moment ,CPU Always run a process , Other processes are not running . In a workshop , There can be a lot of workers . They worked together on a task . Threads are like workers in a workshop , A process can include multiple threads .


2.thread modular

Python thread The module can call the following functions to realize multithreading . It will generate a new thread , In a new thread, use the specified parameters and optional kwargs To call this function .

  • start_new_thread(function, args kwargs=None)

Be careful : When using this method , Be sure to add. time.sleep() function , Otherwise, each thread may not execute . There is another drawback to this approach , It's a complicated problem , The number of threads is not easy to control .

# -*- coding: utf-8 -*-
import _thread
import time
def fun1():
print("hello world %s" % time.ctime())
# Multithreading 
def main():
_thread.start_new_thread(fun1, ()) # No parameter 
_thread.start_new_thread(fun1, ())
time.sleep(2)
print("over")
# The program successfully runs two functions at the same time 
if __name__ == '__main__':
main()

The output result is shown in the figure below :

 Insert picture description here


3.threading modular

thread The module has some disadvantages , In particular, the number of threads cannot be controlled . Use threading Solve the problem that the number of threads can be controlled .

  • Use threading modular
  • Subclass Thread class
# -*- coding: utf-8 -*-
import threading
import time
import sys
def fun1(key):
sys.stdout.write('hello %s:%s \n'%(key, time.ctime()))
def main():
threads = []
keys = ['a', 'b', 'c']
# Number of threads 
threads_count = len(keys)
for i in range(threads_count):
t = threading.Thread(target=fun1, args=(keys[i],))
threads.append(t)
for i in range(threads_count):
threads[i].start()
for i in range(threads_count):
threads[i].join()
if __name__ == '__main__':
main()

The output result is shown in the figure below , Three threads happen at the same time .

 Insert picture description here

Multithreading threading Method can control the number of threads , For example, I want to write requests modular , Get the website's status_code Status code .

# -*- coding: utf-8 -*-
import threading
import time
import requests
import sys
def fun1():
time_start = time.time()
r = requests.get(url="http://www.eastmountyxz.com/")
times = time.time() - time_start
#print('Status:%s--%s--%s'%(r.status_code, times, time.strftime('%H:%M:%S')))
sys.stdout.write('Status:%s--%s--%s\n'%(r.status_code, times, time.strftime('%H:%M:%S')))
def main():
threads = []
# Number of threads Web access 10 Time 
threads_count = 10
for i in range(threads_count):
t = threading.Thread(target=fun1, args=())
threads.append(t)
for i in range(threads_count):
threads[i].start()
for i in range(threads_count):
threads[i].join()
if __name__ == '__main__':
main()

The output result is shown in the figure below :

 Insert picture description here



Two . Programming to realize ping scanning

The above code simply explains thread and threading Multi threaded use of modules . But what's the use in practice ? We can use it for all C The address of the segment is scanned ,ping To see if it's alive , The code is as follows .

# -*- coding: utf-8 -*-
import time
from subprocess import Popen, PIPE
def ping_check():
ip = '127.0.0.1'
#ping Stop after a specified number of times ping But the access was denied Options -c Need to have administrative authority 
#check = Popen("ping -c 3 {0} \n".format(ip), stdin=PIPE, stdout=PIPE, shell=True)
check = Popen("ping {0} \n".format(ip), stdin=PIPE, stdout=PIPE, shell=True)
data = check.stdout.read() # data 
print(data.decode("gbk"))
# The program successfully runs two functions at the same time 
if __name__ == '__main__':
ping_check()

If you enter ip The address is local 127.0.0.1, Then output the normal connection result , As shown below .

 Insert picture description here

If you enter ip The address is local 220.0.0.1, You will be prompted to time out , As shown in the figure below .

 Insert picture description here

And then think about it : How to treat a C Section URL ping Detection ?
The basic idea is to design a loop , If the host doesn't exist , The return is timeout; If the host exists , It contains TTL word , Here we use TTL To judge by , To judge the survival data .

# -*- coding: utf-8 -*-
import time
from subprocess import Popen, PIPE
def ping_check():
ip = '127.0.0.1'
check = Popen("ping {0} \n".format(ip), stdin=PIPE, stdout=PIPE, shell=True)
data = check.stdout.read() # data 
data = data.decode("gbk") # Encoding conversion :byte->str
if 'TTL' in data: # Survive 
print('UP')
# The program successfully runs two functions at the same time 
if __name__ == '__main__':
ping_check()

The output is “UP”.



3、 ... and . testing IP Survival address

Next we try to detect ichunqiu Website ip Address survival . First , call ping Command to detect the site's ip Address , namely :117.23.xx.xx.( This part refers to i spring and autumn ADO teacher , Thank you again for )

 Insert picture description here

There will be ping_check() Function to set a pass parameter , Corresponding ip Address , Detect it ; adopt thread Thread realize ip Address survivability detection , Can detect a lot of live hosts .

# -*- coding: utf-8 -*-
import _thread
import time
from subprocess import Popen, PIPE
def ping_check(ip):
check = Popen("ping {0} \n".format(ip), stdin=PIPE, stdout=PIPE, shell=True)
data = check.stdout.read() # data 
data = data.decode("gbk") # Encoding conversion :byte->str
if 'TTL' in data: # Survive 
print('%s is UP' % ip)
# The main function 
if __name__ == '__main__':
# Look for the target ichunqiu 117.23.xx.xx
for i in range(1,255):
ip = '117.23.xx.' + str(i)
# Multithreading approach 
_thread.start_new_thread(ping_check, (ip, ))
time.sleep(0.1)

The output result is shown in the figure below , among IP Values are also recognized .

 Insert picture description here

problem :
In multithreaded programming , Several threads are started at the same time , So the output is also output in one line , So how can we wrap the output ? Here we use the system output to solve .

# -*- coding: utf-8 -*-
import _thread
import time
from subprocess import Popen, PIPE
import sys
def ping_check(ip):
check = Popen("ping {0} \n".format(ip), stdin=PIPE, stdout=PIPE, shell=True)
data = check.stdout.read() # data 
data = data.decode("gbk") # Encoding conversion :byte->str
if 'TTL' in data: # Survive 
sys.stdout.write('%s is UP \n' % ip)
# The main function 
if __name__ == '__main__':
# Look for the target ichunqiu 1.31.128.240
for i in range(1,255):
ip = '1.31.xx.' + str(i)
# Multithreading approach 
_thread.start_new_thread(ping_check, (ip, ))
time.sleep(0.1)

Output results by line , As shown in the figure below :

 Insert picture description here



Four . Programming port scanner

When we get a website through, we need to scan its open ports , For example, through online tools TScan The scanning results are shown in the following figure , It's open 80、443、8080、7777 Wait for the port . Then whether we can pass Python Write code to realize ? Be similar to NMAP The function of .

 Insert picture description here

1.socket Method

Python The scan port can be accessed through socket Communication implementation , Through establishment TCP Socket , Send... To the port TCP SYN Data packets , And wait for TCP ACK The corresponding , To determine if the port is open .

Complete code :

# -*- coding: utf-8 -*-
import optparse
import socket
from socket import *
#Socket Connect 
def connScan(tgtHost, tgtPort):
try:
conn = socket(AF_INET, SOCK_STREAM)
conn.connect((tgtHost, tgtPort))
#conn.send('Violent Python\n')
#results = conn.recv(100)
print(' [+] %d/tcp open ' % tgtPort)
except Exception as err:
print(' [-] %d/tcp closed' % tgtPort)
#print(err)
finally:
conn.close()
# Scan port 
def portScan(tgtHost, tgtPorts):
try:
tgtIP = gethostbyname(tgtHost)
print(tgtIP)
except:
print("[-] Cannot resolve '%s': Unknown host" % tgtHost)
try:
tgtName = gethostbyaddr(tgtIP)
print("[+] Scan Results for: " + tgtName[0])
except:
print("[+] Scan Results for: " + tgtIP)
setdefaulttimeout(1)
for tgtPort in tgtPorts:
print(" Scanning port " + tgtPort)
# Connection port 
connScan(tgtHost, int(tgtPort))
# The main function optparse Used to process command line arguments 
def main():
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='string', \
help='specify target port[s] separated by comma')
# Parse the parameter values entered by the script 
(options, args) = parser.parse_args()
tgtHost = options.tgtHost
tgtPorts = str(options.tgtPort).split(',')
if (tgtHost==None) or (tgtPorts[0]==None):
print('[-] You must specify a target host and port[s].')
# Port scanning 
portScan(tgtHost, tgtPorts)
if __name__ == '__main__':
main()

This code uses optparse Parameters are defined , Including what needs to be scanned host And the ports that need to be scanned , The results are shown in the following figure , Success will open the port 80、443、777、9080 Identify it .

 Insert picture description here

Again , We can also simply write the above code , Customize IP The port sequence is scanned .

# -*- coding: utf-8 -*-
import socket
# Scan port 
def get_ip_status(ip,port):
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
server.connect((ip,port))
print('{0} port {1} is open'.format(ip, port))
except Exception as err:
print('{0} port {1} is not open'.format(ip,port))
finally:
server.close()
if __name__ == '__main__':
host = '210.40.xx.xx'
for port in range(20,100):
get_ip_status(host,port)

The output is as follows :

 Insert picture description here


2.telnetlib Method

Let's refer to Dahlhin The writings of the great god , Add Python Built-in module telnetlib, It can also complete the port detection task .

# -*- coding: utf-8 -*-
import telnetlib
# Port scanning 
def get_ip_status(ip,port):
server = telnetlib.Telnet() # Create a Telnet object 
try:
server.open(ip,port) # utilize Telnet Object's open methods tcp link 
print('{0} port {1} is open'.format(ip, port))
except Exception as err:
print('{0} port {1} is not open'.format(ip,port))
finally:
server.close()
if __name__ == '__main__':
host = '210.40.xx.xx'
for port in range(20,100):
get_ip_status(host,port)

The output is the same 80 Port open , We can expand the scope of the scan , But it's very slow .


3. Multithreaded scanning

Introduce multithreading threading Module to achieve multi thread scanning , At this point, we only show the open ports .

import telnetlib
import threading
import queue
#IP Port development testing 
def get_ip_status(ip):
server = telnetlib.Telnet()
for port in range(20,10000):
try:
server.open(ip,port)
print('{0} port {1} is open'.format(ip, port))
except Exception as err:
#print('{0} port {1} is not open'.format(ip,port))
pass
finally:
server.close()
def check_open(q):
try:
while True:
ip = q.get_nowait()
get_ip_status(ip)
except queue.Empty as e:
pass
# The main function 
if __name__ == '__main__':
host = ['210.40.xx.xx'] # Analog many IP Address 
q = queue.Queue()
for ip in host:
q.put(ip)
threads = []
for i in range(10):
t = threading.Thread(target=check_open,args=(q,))
t.start()
threads.append(t)
for t in threads:
t.join()


5、 ... and . Multithreading +Queue Realization C Segment scan

although threading The number of threads can be controlled , But when it comes to complex problems , For example, producer and consumer issues , It still can't be solved well .

producer - Consumer issues and Queue modular :

  • Queue modular :qsize()、empty()、full()、put()、get()
  • Perfect match :Queue+Thread

Producer and consumer issues
Producers produce goods , Put the goods in the queue data , When producers produce these goods , Its timing is uncertain ; When survival gives goods to consumers , The time consumed is also uncertain ; Because neither time is certain , There are some problems in multithreading programming . Introduce here Queue The module solves the problem (Python3 The import into the warehouse is queue,Python2 by Queue).

import queue
queue = queue.Queue()
for i in range(10):
queue.put(i)
print(queue.empty())
print(queue.qsize())
# Take the data get Take out the data in turn 
print(queue.get())
print(queue.get())

The output is as follows :

 Insert picture description here

Producers use Queue Put all the data goods in order Queue, Then the consumer takes out Queue Data in . Then implement C Segment scan .

# -*- coding: utf-8 -*-
# By:CSDN Eastmount 2019-10-05
import threading
import queue
import sys
from subprocess import Popen, PIPE
# Define a class Pass in the parameter queue
class DoRun(threading.Thread):
def __init__(self, queue):
threading.Thread.__init__(self)
self._queue = queue
def run(self):
# Non null data 
while not self._queue.empty():
ip = self._queue.get()
#print ip
check_ping = Popen("ping {0} \n".format(ip), stdin=PIPE, stdout=PIPE, shell=True)
data = check_ping.stdout.read()
data = data.decode("gbk")
if 'TTL' in data:
sys.stdout.write(ip+' is UP.\n')
def main():
threads = []
threads_count = 100
q = queue.Queue()
# Put in ip Address 
for i in range(1, 255):
q.put('210.40.81.' + str(i))
for i in range(threads_count):
threads.append(DoRun(q))
for i in threads:
i.start()
for i in threads:
i.join()
if __name__ == '__main__':
main()

The final output is shown in the figure below , Through this code, you can detect a website ip Segment survival .

 Insert picture description here



6、 ... and . summary

I hope this article can help you , This is a Python Black hat's third blog , Programming realizes IP And port scanner 、 Implement multithreading C Segment scanner . The follow-up author will also continue to study in depth , Make some common gadgets for your communication , Of course, you can also talk to NMAP This kind of tool compares , but Python Sometimes it allows you to integrate more powerful and free tools .

Last , Thank you for your attention “ Na Zhang's home ” official account , I hope my article can accompany you to grow up , Hope to keep moving forward on the road of technology . If the article is helpful to you 、 Have an insight , It's the best reward for me , Let's see and cherish ! Thank you again for your attention , Please help to promote it “ Na Zhang's home ”, ha-ha ~ Newly arrived , Please give me more advice .

above :

I'm homesick o(╥﹏╥)o

 Insert picture description here

(By: Na Zhang AI Safe house Eastmount 2020-09-17 Night in Wuhan )


reference :

版权声明
本文为[Eastmount]所创,转载请带上原文链接,感谢

  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database