Сломанная труба и соединение отказались от ошибок
Я пытаюсь создать разумный netcat самостоятельно (все еще довольно новый), добавив дополнительный импорт, флаги и т. д. с помощью модулей netcat и python, мне удалось отладить несколько ошибок, но изменение одной строки кода дает мне 2 разных ошибки. Гугл, ища их обоих, я понял, что может быть много вариантов, почему я получаю это... я надеялся, что кто-то здесь может помочь мне найти точно, какой это вариант.
Мой код:
#import the modules you need
import sys
import os
import threading
import socket
import getopt
import time
import subprocess
#set global variables
lis = False
com = False
up = False
tar = ""
exe = ""
up_d = ""
pt = 0
#runs a command and returns output
def run_com(com):
#trims the newline
com = com.rstip()
#get the output after running the command
try:
output = subprocess.check_output(com,stderr=subprocess.STDOUT, shell=True)
except:
output = "Failed to execute.\r\n"
#send output back to client
return output
def netcat(tar,pt,content):
#if no target is defined listen on all interfaces
if not len(tar):
tar = "0.0.0.0"
#initialize the connection
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((tar,pt))
sock.listen(5)
sock.sendall(content)
while True:
client_socket, addr = sock.accept()
#spin off a thread to handle the new client
client_thread = threading.Thread(target=client_handler,args=(client_socket,))
client_thread.start()
res = ""
while True:
data = sock.recv(1024)
if (not data):
break
res += data.decode()
print(res)
print("Connection closed.")
sock.close()
content = "GET / HTTP/1.1\nHost: google.com\n\n"
netcat(tar,pt,content.encode())
#create a raw socket and bind it to the public interface
def sniffer():
if os.name == "nt":
socket_protocol = socket.IPPROTO_IP
else:
socket_protocol = socket.IPPROTO_ICMP
sniffer = socket.socket(socket.AF_INET,socket.SOCK_RAW,socket_protocol)
sniffer.bind((hn,p))
#include the IP headers in the capture
sniffer.setsockopt(socket.IPPROTO_IP,socket.IP_HDRINCL,1)
#if using windows, send an IOCTL to set up promiscuous mode
if os.name == "nt":
sniffer.icotl(socket.SIO_RCVALL,socket.RCVALL_ON)
#read a single packet
print (sniffer.recvfrom(65565))
#turn off promiscious mode if still using windows
if os.name == "nt":
sniffer.ioctl(socket.SIO_RCVALL,socket.RCVALL_OFF)
def sleeper():
while True:
#get user input
num = input('How long to wait: ')
#try to convert it to a float
try:
num = float(num)
except ValueError:
print('Please enter in a number.\n')
continue
#run time.sleep() and show the before/after time
print('Before: %s' % time.ctime())
time.sleep(num)
print('After: %s\n' % time.ctime())
try:
sleeper()
except KeyBoardInterrupt:
print('\n\nKeyboard exception received. Exiting.')
exit()
def client_handler(client_socket):
global up
global exe
global com
#checking for upload
if len(up_d):
#read in all the bytes and write to the destination
file_buff = ""
#keep reading until none left
while True:
data = client_socket.recv(1024)
if (not data):
break
else:
file_buff += data.decode()
#now take the bytes and try to write them out
try:
file_desc = open(up_d,"wb")
file_desc.write(file_buff)
file_desc.close()
#acknowledge it's been written
client_socket.send("Success! file saved to %s\r\n" % up_d)
except:
client_socket.send("Failed! file wasn't saved to %s\r\n" % up_d)
#check for command execution
if len(exe):
#run command
output = run_com(exe)
client_socket.send(output)
#if shell was requested go into another loop
if com:
while True:
#show a prompt
client_socket.send("<action:#>")
#now receieve until a linefeed is seen
cmd_buff = ""
while ("\n" not in cmd_buff):
cmd_buff += client_socket.recv(1024)
#execute the command and send back results
res = run_com(cmd_buff)
#send back response
client_socket.send(res)
#type netcat -h in the terminal to see the commandline options and change them to your liking
def usage():
print ("netcat python3")
print
print ("Usage: netcat3.py -t target_host -p port")
print ("-l --listen - listen on [host]:[port] for incoming connections")
print ("-e --execute - program to execute after connection")
print ("-c --shell command - initalize a command shell")
print ("-u --upload=destination - upon receving connection upload a file and write to[destination]")
print
print ("Examples: ")
print ("netcat3.py -t 127.0.0.1 -p 8080 -l -c")
print ("netcat3.py -t 127.0.0.1 -p 8080 -l -u=c:\\target.exe")
print ("netcat3.py -t 127.0.0.1 -p 8080 -l -e=\"cat /etc/passwrd\"")
print ("echo 'HELLO' | python3 netcat3.py -t 45.56.155.187 -p 135")
sys.exit(0)
def main():
global lis
global pt
global exe
global com
global up_d
global tar
if not len(sys.argv[1:]):
usage()
#read the commandline options
try:
opts, args = getopt.getopt(sys.argv[1:],"hle:t:p:cu:",["help","lis","exe","tar","p","com","up"])
except getopt.GetoptError as err:
print (str(err))
usage()
for o,a in opts:
if o in ("-h","--help"):
usage()
elif o in ("-l","--listen"):
lis = True
elif o in ("-e","--execute"):
exe = a
elif o in ("-c","--commandshell"):
com = True
elif o in ("-u","--upload"):
up_d = a
elif o in ("-t","--target"):
tar = a
elif o in ("-p","--port"):
pt = int(a)
else:
assert False, "Unhandled Option"
#listen or just send data from stdin?
if not lis and len(tar) and pt > 0:
#read the buffer from the commandline, send CTRL-D if not sending input to stdin
buff = sys.stdin.read()
#send off data
client_sender(buffer)
#depending on the commands in the options above might listen and potentially upload things
#execute commands and drop a shell back
if lis:
serv_loop()
main()
Первая ошибка при наличии "sock.connect((tar,pt))":
anon@kali:~/Desktop/python scripts$ python3 netcat3.py -l -p 9999 -c
Traceback (most recent call last):
File "netcat3.py", line 68, in <module>
netcat(tar,pt,content.encode())
File "netcat3.py", line 41, in netcat
sock.connect((tar,pt))
ConnectionRefusedError: [Errno 111] Connection refused
если я изменю строку, указанную выше, на "socket.bind((tar,pt))", ошибка будет такой:
anon@kali:~/Desktop/python scripts$ python3 netcat3.py -l -p 9999 -c
Traceback (most recent call last):
File "netcat3.py", line 68, in <module>
netcat(tar,pt,content.encode())
File "netcat3.py", line 44, in netcat
sock.sendall(content)
BrokenPipeError: [Errno 32] Broken pipe
я знаю, что это может быть что-то простое, или я переусердствовал в своем коде, но что бы это ни было, я застрял в поиске главной проблемы, как пройти эту стену. Заранее спасибо за любую помощь, я действительно ценю это.