基于python3编写

import sys, socket, getopt, threading, argparse, subprocess

# globals options
listen = False
command = False
upload = None
execute = None
target = None
upload_destination = None
port = None def main():
global target
global command
global execute
global listen
global upload_destination
global port # set up argument parsing
parser = argparse.ArgumentParser(description="netcat clone")
parser.add_argument("-p","--port", type=int, help="target port")
parser.add_argument("-t", "--target_host", type=str, help="target host", default="0.0.0.0")
parser.add_argument("-l", "--listen", help="listen on [host]:[port} for incomming connections", action="store_true",default=False) # action 有参数为true,没有参数default false
parser.add_argument("-e", "--execute", help="execute file-to-run execute the given file upn receiving a connection")
parser.add_argument("-c", "--command", help="initialize a command shell", action="store_true", default=False)
parser.add_argument("-u", "--upload",help="--upload=destination upon receing connection upload and write to destination")
args = parser.parse_args() # parse arguments
target = args.target_host
port = args.port
listen = args.listen
execute = args.execute
command = args.command
upload_destination = args.upload # if listen is false and send send data from stdin
if not listen and target is not None and port > 0:
print("DBG:read data from stdin")
# read buffer from stdin , this will block so send CTRL-D if not
# sending to stdin 从stdin发送
buff = sys.stdin.read() print("Sending {0} to client".format(buff))
# send data
client_sender(buff) # we are going to listen and potentially upload things ,excute
# commands and drop a shell back ,depending on the command line options
if listen:
server_loop() def client_sender(buff):
print("DBG:sending data to client on port" + str(port)) # create a sockets
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try:
# connect to target host
client.connect((target, port)) if len(buff):
client.send(buff.encode())
while True:
# now let's wait for data response
recv_len = 1
response = "" while recv_len:
print("DBG:waiting for response from client")
data = client.recv(4096)
recv_len = len(data)
response += data.decode(errors="ignore") if recv_len < 4096:
break
# end="" statement does not end
print(response, end="") # wait for more input
buff = input("")
buff += "\n"
# send it off
client.send(buff.encode())
except:
print("[*] Exception! Exiting.")
finally:
client.close() def server_loop():
global target
print("DBG:entering server loop") server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((target, port)) server.listen(5) while True:
client_socket, addr = server.accept() # spin a thread to handle the new client
client_thread = threading.Thread(target=client_handler, args=(client_socket,))
client_thread.start() def run_command(command):
# trim the newline rstrip trim the end of newline
command = command.rstrip()
print("DGB:executing command:" + command) try:
# this will launch a new process ,note:cd commands are useless
output = subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True)
except:
output = "Failed to execute to command.\r\n" # send the output back to the client
return output # 服务端监听,获取从客户端发来的数据执行命令
def client_handler(client_socket):
global upload
global execute
global command
print("DBG:handling client socket") # check for upload
if upload_destination is not None:
print("DEBG:entering file upload") # read all of the bytes and write them to the destination
file_buff = "" # keep reading data until none is available
while True:
data = client_socket.recv(1024)
if not data:
break
else:
file_buff += data.decode() # write bytes to file
try:
f = open(upload_destination, "wb")
f.write(file_buff)
f.close() # ACK file writing
client_socket.send("Successfully saved file to {0}\r\n".format(upload_destination).encode())
except:
client_socket.send("Failed to save file to {0}\r\n".format(upload_destination).encode()) if execute is not None:
print("DBG: going to execute command") # run the command
output = run_command(execute)
client_socket.send(output.encode()) # go into loop if a command shell was resquested
if command:
print("DBG:shell requested") # show a prompt
client_socket.send("<BHP:#>".encode())
while True: # now recieve until linefeed
cmd_buff = ""
while "\n" not in cmd_buff:
cmd_buff += client_socket.recv(1024).decode() # send back the command output
response = run_command(cmd_buff) # 判断一个response是否为str类型
if isinstance(response, str):
response = response.encode() # send back the response
client_socket.send(response + "<BHP:#>".encode()) if __name__ == '__main__':
main()

  使用实列:

服务端执行:

python necat_1.py -l -p  -c

客户端执行:

python nccat_1.py -t localhost -p 9999

客户端执行需要EOF读取结束,linux(ctrl-d),windows(ctrl-z)

PYTHON 黑帽子第二章总结的更多相关文章

  1. python黑帽子(第二章)

    TCP客户端 在渗透测试工程中,我们经常会遇到需要创建一个TCP客户端来连接网络.发送垃圾数据.进行模糊测试等任务的情况.但是所处环境不具备丰富的网络工具,下面是一个简单的TCP客户端 import ...

  2. Python 黑帽子第二章运行截图

  3. 读书笔记 ~ Python黑帽子 黑客与渗透测试编程之道

    Python黑帽子  黑客与渗透测试编程之道   <<< 持续更新中>>> 第一章: 设置python 环境 1.python软件包管理工具安装 root@star ...

  4. 2017-2018-2 20179204 PYTHON黑帽子 黑客与渗透测试编程之道

    python代码见码云:20179204_gege 参考博客Python黑帽子--黑客与渗透测试编程之道.关于<Python黑帽子:黑客与渗透测试编程之道>的学习笔记 第2章 网络基础 t ...

  5. 《零压力学Python》 之 第二章知识点归纳

    第二章(数字)知识点归纳 要生成非常大的数字,最简单的办法是使用幂运算符,它由两个星号( ** )组成. 如: 在Python中,整数是绝对精确的,这意味着不管它多大,加上1后都将得到一个新的值.你将 ...

  6. python黑帽子(第五章)

    对开源CMS进行扫描 import os import queue import requests # 原书编写时间过于久远 现在有requests库对已经对原来的库进行封装 更容易调用 import ...

  7. python黑帽子(第四章)

    Scapy窃取ftp登录账号密码 sniff函数的参数 filter 过滤规则,默认是嗅探所有数据包,具体过滤规则与wireshark相同. iface 参数设置嗅探器索要嗅探的网卡,默认对所有的网卡 ...

  8. python黑帽子(第三章)

    Windows/Linux下包的嗅探 根据os.name判断操作系统 下面是os的源码 posix是Linux nt是Windows 在windows中需要管理员权限.linux中需要root权限 因 ...

  9. python基础教程-第二章-列表和元组

    本章将引入一个新的概念,:数据结构.数据结构是通过某种方式(例如对元素进行编号)组织在 一起的数据元素的集合,这些数据元素可以是数字或者字符,甚至可以是其他数据结构.在python中,最基本的数据结构 ...

随机推荐

  1. 【面试题】String类、包装类的不可变性

    不可变类的意思是创建该类的实例后,该实例的实例变量是不可改变的.Java提供的8个包装类和String类都是不可变类.因此String和8个包装类都具有不可变性. 就拿String类来说,通过阅读St ...

  2. js 箭头函数不适用的场景

    箭头函数虽然方便但也不是每个地方都适用, 箭头函数在开发中可以十分方便的干预 this的指向,在一些情况下,是不需要对this的指向进行干预的,也就不适用箭头函数 1.构造函数的原型方法上 例如:Pe ...

  3. Spring Cloud学习 之 Spring Cloud Ribbon(负载均衡器源码分析)

    文章目录 AbstractLoadBalancer: BaseLoadBalancer: DynamicServerListLoadBalancer: ServerList: ServerListUp ...

  4. 使用 pyautogui 进行跨平台的 GUI 自动化操作

    有个朋友最近问我有没有推荐 GUI 桌面应用自动化的技术,我只能回答他:不好意思,这个真有,他是 pyautogui.主要有三大特征: 纯纯的 python, 源码一览无余: 跨平台,linux, w ...

  5. web2

    0x01 <?php $miwen="a1zLbgQsCESEIqRLwuQAyMwLyq2L5VwBxqGA3RQAyumZ0tmMvSGM2ZwB4tws"; funct ...

  6. jQuery学习笔记——jQuery基础核心

    代码风格 在jQuery程序中,不管是页面元素的选择.内置的功能函数,都是美元符号“$”来起始的.而这个“$”就是jQuery当中最重要且独有的对象:jQuery对象,所以我们在页面元素选择或执行功能 ...

  7. java ->大的数据运算(BigInteger)

    大数据运算 BigInteger java中long型为最大整数类型,对于超过long型的数据如何去表示呢.在Java的世界中,超过long型的整数已经不能被称为整数了,它们被封装成BigIntege ...

  8. webpack指南(四)shimming

    shimming 将一个新的 API 引入到一个旧的环境中,而且仅靠旧的环境中已有的手段实现. ProvidePlugin 我们在程序中暴露一个变量,通知webpack某个库被使用,webpack将在 ...

  9. win-sudo插件解决Git bash 执行脚本报错问题 bash: sudo: command not found

    Windows git bash 默认没有sudo命令,可以添加win-sudo插件实现该功能 curl -s https://raw.githubusercontent.com/imachug/wi ...

  10. Socket - TCP编程

    Socket是网络编程的一个抽象概念. 通常我们用一个Socket表示“打开了一个网络链接”,而打开一个Socket需要知道目标计算机的IP地址和端口号,再指定协议类型即可 socket参数及常用功能 ...