目錄
注:本文章用於博主蒐集python腳本,對於可以運行的腳本進行彙總和結果展示,大部分代碼來源於網絡,侵刪。
爬取免費HTTP及HTTPS代理
#!/usr/bin/env python3
# coding:utf-8
# date:2019/04/17
# 免費代理爬取
from gevent import monkey
monkey.patch_all()
import gevent
import requests
from bs4 import BeautifulSoup
headers = {
'User-Agent': 'Mozilla/8.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36'
}
class GetProxy:
def __init__(self):
self.ip_https_list_tmp = set()
self.ip_http_list_tmp = set()
self.ip_https_list = set() # 篩選之後的https代理
self.ip_http_list = set() # 篩選之後的http的代理
def get(self):
self._xicidaili(5)
gevent.joinall([gevent.spawn(self._check) for i in range(0, 100)])
def _xicidaili(self, pages=5):
# 西刺免費代理IP https://www.xicidaili.com
for page in range(0, pages):
url = "https://www.xicidaili.com/nt/{}".format(page)
r = requests.get(url, headers=headers)
soup = BeautifulSoup(r.text, 'lxml')
trs = soup.find_all('tr')
for i in range(1, len(trs)):
tr = trs[i]
tds = tr.find_all("td")
ip_item = tds[5].text.lower() + "://" + tds[1].text + ":" + tds[2].text
if ip_item[:5] == "https":
self.ip_https_list_tmp.add(ip_item)
elif ip_item[:4] == "http":
self.ip_http_list_tmp.add(ip_item)
def _check(self):
# 用百度驗證https代理
while len(self.ip_https_list_tmp) > 0:
ip_for_test = self.ip_https_list_tmp.pop()
proxies = {
'https': ip_for_test
}
try:
response = requests.get('https://www.baidu.com', headers=headers, proxies=proxies, timeout=3)
if response.status_code == 200:
self.ip_https_list.add(ip_for_test)
except:
continue
# 驗證http代理
while len(self.ip_http_list_tmp) > 0:
ip_for_test = self.ip_http_list_tmp.pop()
proxies = {
'http': ip_for_test
}
try:
response = requests.get('http://httpbin.org/ip', headers=headers, proxies=proxies, timeout=3)
if response.status_code == 200:
self.ip_http_list.add(ip_for_test)
except:
continue
if __name__ == "__main__":
Proxy = GetProxy()
Proxy.get()
print("https代理:")
print(Proxy.ip_https_list)
print("http代理:")
print(Proxy.ip_http_list)
地址段IP發現
import ipaddress
import multiprocessing
import random
from scapy.layers.inet import IP, ICMP
from scapy.sendrecv import sr1
DIP = "121.17.123.1/24"
BNUM = 20
TNUM = 64
def getBytes(num):
res = ''.join(random.sample('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567', num))
return bytes(res, encoding='utf-8')
def ping(ip):
pkt = IP(dst=ip) / ICMP() / getBytes(BNUM)
res = sr1(pkt, timeout=5, verbose=False)
if res:
return True, ip
else:
return False, ip
def getIpList(ip):
temp = ipaddress.ip_network(ip, False).hosts()
ipList = []
for i in temp:
ipList.append(str(i))
return ipList
def ipScan(ip, num):
ipList = getIpList(ip)
pool = multiprocessing.Pool(processes=int(TNUM))
result = pool.map(ping, ipList)
pool.close()
pool.join()
for res, ip in result:
if res:
print(ip)
if __name__ == "__main__":
ipScan(DIP, TNUM)
這個腳本自己寫的,還不會寫參數,只好弄全局變量了,地址是我隨便敲的,各位看官不要一直ping人家,換一個地址段試試。
端口掃描
# /usr/bin/env python3
# _*_ coding:utf-8 _*_
# auther: saucerman
# project: https://github.com/saucer-man/penetration-script
"""
基於python-nmap的端口掃描器
pip install python-nmap
"""
import sys
import time
from colorama import init, Fore, Back, Style
import getopt
# 顏色定義
init(autoreset=True)
class Colored(object):
def red(self, s):
return Fore.RED + s + Fore.RESET
def blue(self, s):
return Fore.BLUE + s + Fore.RESET
def yellow(self, s):
return Fore.YELLOW + s + Fore.RESET
color = Colored()
try:
import nmap
except:
print("FATAL: Module nmap missing (python-nmap)")
sys.exit(1)
# 使用說明
def usage():
print(color.blue('Usage: port scanner'))
print(color.blue('\t-h/--host:\tpoint the target to scan'))
print(color.blue('\t-p/--port:\tpoint the port to scan(not nessesary)'))
print(color.blue('Examples:'))
print(color.blue('\tpython port_scanner.py -h 10.10.10.1'))
print(color.blue('\tpython port_scanner.py -h 10.10.10.1 -p 80,443,8080'))
print(color.blue('\tpython port_scanner.py -h 10.10.10.1 -p 1-1024'))
print(color.blue('\nSEE THE MAN PAGE (https://github.com/saucer-man/saucer-frame) FOR MORE OPTIONS AND EXAMPLES'))
sys.exit(0)
# 掃描
def scanner(host, ports):
nm = nmap.PortScanner()
try:
print('Scanner report for %s\n' % host)
if len(ports) == 0:
result = nm.scan(host)
else:
result = nm.scan(host, ports)
if result['nmap']['scanstats']['uphosts'] == '0':
print(color.red('Host seems down'))
else:
print('Host is up')
print("{:<7}\t{:<7}\t{:<7}\t{:<7}".format('PORT', 'STATE', 'SERVICE', 'VERSION'))
for k, v in result['scan'][host]['tcp'].items():
if v['state'] == 'open':
print(color.yellow("{:<7}\t{:<7}\t{:<7}\t{:<7}".format(str(k), v['state'], v['name'],
v['product'] + v['version'])))
else:
print(color.yellow("{:<7}\t{:<7}".format(str(k), v['state'])))
except Exception as e:
print(color.red("unhandled Option"))
usage()
def main():
start = time.time()
# 解析命令行
if not len(sys.argv[1:]):
usage()
try:
opts, args = getopt.getopt(sys.argv[1:], "h:p:",
["host=", "port="])
except:
print(color.red("unhandled Option"))
usage()
ports = ''
for o, a in opts:
if o == "-h" or o == "--host":
host = a
elif o == "-p" or o == "--port":
ports = a
print("Starting port scanner...")
scanner(host, ports)
end = time.time()
print('\n\nScanner down with %0.6f seconds.' % (end - start))
if "__main__" == __name__:
main()
右側是我使用nmap進行的掃描。
更多內容查看:網絡安全-自學筆記
有問題請下方評論,轉載請註明出處,並附有原文鏈接,謝謝!如有侵權,請及時聯繫。