Skip to content

Instantly share code, notes, and snippets.

@keepitsimple
Last active November 20, 2022 16:48
Show Gist options
  • Save keepitsimple/1de1306a396d5534d7f3302e606ba72a to your computer and use it in GitHub Desktop.
Save keepitsimple/1de1306a396d5534d7f3302e606ba72a to your computer and use it in GitHub Desktop.
aiohttp + aiosocks: async tor proxy example
import asyncio
import aiohttp
import aiosocks
from aiosocks.connector import ProxyConnector, ProxyClientRequest
async def main():
async with aiohttp.ClientSession() as session:
async with session.get('http://icanhazip.com/') as resp:
body = await resp.text()
host_ip = body.strip()
print('ip: {}'.format(host_ip))
conn = ProxyConnector(remote_resolve=False)
try:
async with aiohttp.ClientSession(connector=conn, request_class=ProxyClientRequest) as session:
async with session.get('http://icanhazip.com/', proxy='socks5://127.0.0.1:9060') as resp:
body = await resp.text()
tor_ip = body.strip()
print('tor ip: {}'.format(tor_ip))
except aiohttp.ClientProxyConnectionError:
# connection problem
pass
except aiohttp.ClientConnectorError:
# ssl error, certificate error, etc
pass
except aiosocks.SocksError:
# communication problem
pass
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment