Replacing Netcat:绝对可以运行,还发现了原著2处代码错误,已经改正,目前仅实现了-e参数
其他参数类似
import socket
import threading
import argparse
import subprocess
import sys
import textwrap
import shlex
def execute(cmd):
cmd = cmd.strip()
if not cmd:
return
output = subprocess.check_output(shlex.split(cmd), stderr=subprocess.STDOUT)
return output
class NetCat:
def __init__(self, args, buffer):
self.args = args
self.buffer = buffer
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
def run(self):
if self.args.listen:
self.listen()
else:
self.sender()
def listen(self):
print("listening\n")
self.socket.bind((self.args.target, self.args.port))
self.socket.listen(5)
while True:
client_socket, address = self.socket.accept()
print('####')
print(address)
print('####')
client_thread = threading.Thread(target=self.handler, args=(client_socket,))
client_thread.start()
def handler(self, client_socket):
if self.args.execute:
print('client is acting!')
output=execute(self.args.execute)
client_socket.send(output)
def sender(self):
print('connecting\n')
self.socket.connect((self.args.target, self.args.port))
if self.buffer:
self.socket.send(self.buffer.encode())
try:
print('action\n')
while True:
recv_len = 1
response = ''
while recv_len:
data = self.socket.recv(4096)
recv_len = len(data)
response += data.decode()
if recv_len < 0:
break
if response:
print(response)
buffer = input('>')
buffer += '\n'
self.socket.send(buffer.encode())
except KeyboardInterrupt:
print('USER INTERRUPTED')
self.socket.close()
sys.exit()
def main():
parser = argparse.ArgumentParser(description='BHP Net Tool',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=textwrap.dedent('''Example:
netcat.py -t 192.168.1.108 -p 5555 -l -c # command shell
netcat.py -t 192.168.1.108 -p 5555 -l -u=mytest.txt # upload to file
netcat.py -t 192.168.1.108 -p 5555 -l -e=\"cat /etc/passwd\" # execute command
echo 'ABC' | ./netcat.py -t 192.168.1.108 -p 135 # echo text to server port 135
netcat.py -t 192.168.1.108 -p 5555 # connect to server
'''))
parser.add_argument('-c', '--command', action='store_true', help='command shell')
parser.add_argument('-e', '--execute', help='execute specified command')
parser.add_argument('-l', '--listen', action='store_true', help='listen')
parser.add_argument('-p', '--port', type=int, default=9999, help='specified port')
parser.add_argument('-t', '--target', default='127.0.0.1', help='specified IP')
parser.add_argument('-u', '--upload', help='upload file')
args = parser.parse_args()
print('####\n', args)
print('###\n')
if args.listen:
buffer = ''
else:
buffer = 'i am client'
nc=NetCat(args,buffer)
nc.run()
if __name__ == "__main__":
main()
|