I am trying to understand why a proxy is not connecting to the website, but displays my IP instead
import httpx
import asyncio
proxies = {"http": "http://34.91.135.38:80"}
async def main():
async with httpx.AsyncClient(proxies=proxies) as client:
s = await client.get('https://api.ipify.org')
print(s.text)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
When I try to do that, it will display my IP, not the IP I selected. I want to be able to use my proxy to connect to the website
Related
New to web-facing python applications, and managed to put together a couple of templates to create a template that will serve as foundation for a project-level HTTPS server that handles basic requests.
Is python secure for creating HTTPS servers? Obviously environment is a factor, and I'd plan to run this isolated from other devices on the network. It's going to be providing non-sensitive information that is stored locally on the machine which will support TLS 1.3.
But what else do I need to consider looking out for?
import http.server
import ssl
host = '127.0.0.1'
port = 443
class Handler(http.server.SimpleHTTPRequestHandler):
def _set_response(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
def do_GET(self):
self._set_response()
self.wfile.write("GET request for {}".format(self.path).encode('utf-8'))
def do_POST(self):
content_length = int(self.headers['Content-Length'])
post_data = self.rfile.read(content_length)
self._set_response()
self.wfile.write("POST request for {}".format(self.path).encode('utf-8'))
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain('cert.pem', 'key.pem')
httpd = http.server.HTTPServer((host, port), Handler)
httpd.socket = context.wrap_socket(httpd.socket, server_side=True)
httpd.serve_forever()
This is my first time posting, and I'm in a difficult situation i'd consider somewhat unique.
My Goal and Whats happened so far:
Basically, I just need to pass integers from my desktop PC to a raspberry pi in "real time", preferably over a wireless connection. The code snippets below are versions of the "test program" that employ specifically what I'm having issues with. To achieve this, I'm using the python websockets module
The issue I'm facing is new to me, because previously this program worked entirely as intended, as I lived in a location where I owned my router in a house, but now I live in an apartment complex with special network restrictions (needing to register MAC addresses and such)
Previous Results (When I lived at the previous location)
I achieved the desired results of pasting random integers to the console as fast as possible that were generated from the server PC with the following programs below. Note that when I put i used the IP that could be easily found when you google "what is my IP"
SERVER SIDE (ON THE PC)
import asyncio
import websockets
import random
async def createdata():
return random.randint(0, 15000)
async def senddata(websocket, path):
number = await createdata()
print("sending data")
await websocket.send(str(number))
print(number)
start_server = websockets.serve(senddata, "<INSERTIPHERE>", 4421)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
CLIENT SIDE (ON THE RASP PI)
import asyncio
import websockets
async def datarecieve():
uri = "ws://<INSERTIPHERE>:4421"
async with websockets.connect(uri) as websocket:
data = await websocket.recv()
print(data)
while True:
asyncio.get_event_loop().run_until_complete(datarecieve())
Results Now (Now that I live in the apartment complex)
I get the error thrown on the client side: ConnectionRefusedError: [Errno 111] Connect call failed (ipgoeshere, port). Here are the programs:
SERVER SIDE (ON THE PC)
import asyncio
import websockets
import random
async def createdata():
return random.randint(0, 15000)
async def senddata(websocket, path):
number = await createdata()
print("sending data")
await websocket.send(str(number))
print(number)
start_server = websockets.serve(senddata, "localhost", 4421)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
CLIENT SIDE (ON THE RASP PI)
import asyncio
import websockets
async def datarecieve():
uri = "ws://<externalipofappartmentcomplex>:4421"
async with websockets.connect(uri) as websocket:
data = await websocket.recv()
print(data)
while True:
asyncio.get_event_loop().run_until_complete(datarecieve())
More Information About What I've Tried or What I'm Willing to Do
For the server side, I've also tried ips like: 127.0.0.1, 0.0.0.0, and the ipv4 assigned to the device (found in ipconfig in cmd)
For the Client side, I've also tried the ipv4 assigned to the server device
Opening up the port on the firewall of the server computer
I've considered just buying my own wireless router and hopefully finding luck that way
Thank you for any help.
How do I create a simple HTTP webserver in python 3, that would return a generated content for GET requests?
I checked this question,
How to create a simple HTTP webserver in python?, but the solution proposed will return files, which is not the thing I need.
Instead, my server should respond with a generated response.
I know about frameworks like Flask and Django, but they would be an overkill for me. I need the shortest and the least resource greedy code that will just return generated content for any request.
After a little bit of research, I have come up with this as the simplest possible solution:
from http.server import HTTPServer, BaseHTTPRequestHandler
class MyRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.end_headers()
self.wfile.write(b'My content')
httpd = HTTPServer(('localhost', 5555), MyRequestHandler)
httpd.serve_forever()
You can do so with the http module as shown below:
from http.server import BaseHTTPRequestHandler, HTTPServer
import time
hostname = "localhost"
serverPort = 8080
class Server(BaseHTTPRequestHandler):
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>Python Webserver</title>
</head>", "utf-8"))
self.wfile.write(bytes("<body>", "utf-8"))
self.wfile.write(bytes("<p>Web server is open!</p>", "utf-8"))
self.wfile.write(bytes("</body></html>", "utf-8"))
if __name__ == "__main__":
webServer = HTTPServer((hostname, serverPort), Server)
print("Server started http://%s:%s" % (hostname, serverPort))
try:
webServer.serve_forever()
except KeyboardInterrupt:
pass
webServer.server_close()
print("Server closed")
time.sleep(2)
This code creates a web server on http://localhost:8080 and displays some text saying Web server is open!.
right now i am using the following code to port my python through tor to send requests:
socks.set_default_proxy(socks.SOCKS5, "127.0.0.1", 9450)
socket.socket = socks.socksocket
I put this at the front of my code and then start sending requests, and all my requests will be sent through tor.
In my code I need to send a lot of requests, but only 1 of them needs to actually go through tor. The rest of them don't have to go through tor.
Is there any way I can configure my code so that I can choose which requests to send through tor, and which to send through without tor?
Thanks
Instead of monkey patching sockets, you can use requests for just the Tor request.
import requests
import json
proxies = {
'http': 'socks5h://127.0.0.1:9050',
'https': 'socks5h://127.0.0.1:9050'
}
data = requests.get("http://example.com",proxies=proxies).text
Or if you must, save the socket.socket class prior to changing it to the SOCKS socket so you can set it back when you're done using Tor.
socks.set_default_proxy(socks.SOCKS5, "127.0.0.1", 9450)
default_socket = socket.socket
socket.socket = socks.socksocket
# do stuff with Tor
socket.socket = default_socket
I am trying to connect to two WebSockets (WebSocket A with URI wss://domainA.com and WebSocket B with URI wss://domainB.com/path) using Autobahn running on asyncio as described in the Autobahn docs.
I have created a WebSocketClientProtocol like so:
from autobahn.asyncio.websocket import WebSocketClientProtocol
class ClientProtocol(WebSocketClientProtocol):
def onConnect(self, response):
print("Connected to Server: {}".format(response.peer))
and am connecting to the WebSocket using an asyncio connection:
from autobahn.asyncio.websocket import WebSocketClientFactory
import asyncio
factory = WebSocketClientFactory()
factory.protocol = ClientProtocol
loop = asyncio.get_event_loop()
coro = loop.create_connection(factory, 'domainA.com', 80)
loop.run_until_complete(coro)
loop.run_forever()
loop.close()
I am able to connect to WebSocket A but connecting to WebSocket B by replacing domainA.com with domainB.com/path results in an error gaierror: [Errno 8] nodename nor servname provided, or not known.
I know that WebSocket B is working since I am able to connect to it using a different library. Also, replacing domainB.com/path with just domainB.com results in connection was closed uncleanly (WebSocket connection upgrade failed (301 - MovedPermanently))