Я сейчас читаю книгу Black Hat Python, и автор предоставляет код, который заменяет netcat. Я скопировал код прямо из онлайн-источника, и он не работал. В течение последних нескольких дней я проходил через это и пытался выяснить, что происходит не так, и похоже, что он печатает ответ сервера, а затем продолжает не ждать, пока пользователь введет какие-либо команды. Этот код немного устарел, я полагаю, что он изначально был написан на python 2.7.3, поэтому я не знаю, могут ли некоторые обновления python вызывать проблему. Ниже приведены три функции, которые содержат всю логику для клиента и сервера. Любая помощь с этим была бы великолепна.
def client_sender(buffers):
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
# connect to our target host
client.connect((target,port))
print "[*] Connected to server"
# if we detect input from stdin send it
# if not we are going to wait for the user to punch some in
if len(buffers) > 0:
print "Buffer sent: %s" % buffers
client.send(buffers)
while True:
print "In client_sender loop.."
# now wait for data back
recv_len = 1
response = ""
while recv_len:
data = client.recv(4096)
print "Data from Server: %s" % data
recv_len = len(data)
response+= data
if recv_len < 4096:
break
print response,
# wait for more input
buffers = raw_input("Input: ")
# send it off
client.send(buffers)
print "buffer sent"
except Exception as e:
# just catch generic errors - you can do your homework to beef this up
print "[*] Exception! Exiting."
print e
# teardown the connection
client.close()
# this handles incoming client connections
def client_handler(client_socket):
global upload
global execute
global command
# check for upload
if len(upload_destination):
# read in all of the bytes and write to our destination
file_buffer = ""
# keep reading data until none is available
while True:
data = client_socket.recv(1024)
if not data:
break
else:
file_buffer += data
# now we take these bytes and try to write them out
try:
file_descriptor = open(upload_destination,"wb")
file_descriptor.write(file_buffer)
file_descriptor.close()
# acknowledge that we wrote the file out
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)
# check for command execution
if len(execute):
# run the command
output = run_command(execute)
client_socket.send(output)
# now we go into another loop if a command shell was requested
if command:
while True:
# show a simple prompt
client_socket.send("<BHP:#> ")
# now we receive until we see a linefeed (enter key)
cmd_buffer = ""
while "\n" not in cmd_buffer:
cmd_buffer += client_socket.recv(1024)
print "cmd_buffer: %s" % cmd_buffer
# we have a valid command so execute it and send back the results
response = run_command(cmd_buffer)
# send back the response
client_socket.send(response)
# this is for incoming connections
def server_loop():
global target
global port
# if no target is defined we listen on all interfaces
if not len(target):
target = "0.0.0.0"
print "[*] Listening on %s:%d" % (target, port)
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((target,port))
server.listen(5)
print "[*] Waiting on Client..."
while True:
client_socket, addr = server.accept()
print "[*] Connection Successful"
# spin off a thread to handle our new client
client_thread = threading.Thread(target=client_handler,args=(client_socket,))
client_thread.start()