How to route TCP traffic through Tor proxy? - python-3.x

I would like to create a TCP connection using python library socket. This traffic should be redirected through Tor network but socks.SOCKS5Error: 0x01: General SOCKS server failure is given.
The code below can connect to Tor proxy and gives a new Tor IP.
from stem.control import Controller
from stem import Signal
import socket
import socks
if __name__ == "__main__":
with Controller.from_port(port=9051) as controller:
# Creatting TOR connection
controller.authenticate(password='password')
controller.signal(Signal.NEWNYM)
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "192.168.1.148", 9050)
socket.socket = socks.socksocket
# Creatting socket connection
new_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = '192.168.1.148'
port = 50007
new_socket.connect((host, port))
new_socket.sendall('Hello world')
print(new_socket.recv(1024))
This is the error given:
Traceback (most recent call last):
File "/usr/lib/python3.10/site-packages/socks.py", line 809, in connect
negotiate(self, dest_addr, dest_port)
File "/usr/lib/python3.10/site-packages/socks.py", line 443, in _negotiate_SOCKS5
self.proxy_peername, self.proxy_sockname = self._SOCKS5_request(
File "/usr/lib/python3.10/site-packages/socks.py", line 533, in _SOCKS5_request
raise SOCKS5Error("{:#04x}: {}".format(status, error))
socks.SOCKS5Error: 0x01: General SOCKS server failure
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/pi/keylogger-project/./tor_proxy_connection.py", line 74, in <module>
tor.__testing_socket_availability__()
File "/home/pi/keylogger-project/./tor_proxy_connection.py", line 66, in __testing_socket_availability__
self.socket.connect((host, port))
File "/usr/lib/python3.10/site-packages/socks.py", line 47, in wrapper
return function(*args, **kwargs)
File "/usr/lib/python3.10/site-packages/socks.py", line 814, in connect
raise GeneralProxyError("Socket error", error)
socks.GeneralProxyError: Socket error: 0x01: General SOCKS server failure
Server side is a simple nc -lvp 50007
Regards

socket.socket = socks.socksocket
...
host = '192.168.1.148'
...
new_socket.connect((host, port))
The target 192.168.1.148 is an IP address reserved for private networks and thus not reachable from the internet. But the nodes on the Tor network are on the internet and thus cannot reach the given target.

Related

ESP32 Socket client not connecting to python server

Hey!
Am a developer trying to establish a socket connection between my pc and an esp32 connected on the same network.
Code
On esp32(micropython)
import usocket
import network
def do_connect():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print('connecting to network...')
wlan.connect('whydoesnt', 'itwork')
while not wlan.isconnected():
pass
print('network config:', wlan.ifconfig())
def connect_socket():
addr = ("192.168.1.4", 80)
s = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM)
s.connect(addr)
s.send("hello")
s.close()
do_connect()
connect_socket()
On my computer (python3.9)
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("0.0.0.0", 80))
s.listen(3)
while True:
client, addr = s.accept()
print("Connected by {}".format(addr))
while True:
content = client.recv(32)
if len(content) == 0:
break
else:
print(content)
print("Closing connection")
client.close()
Am hosting the socket server on 0.0.0.0 so that it runs on the wifi network.
Well, the python server works. I tested it using puTTy running on the same pc. I just had to get my ip address from cmd and connect to it using putty.
Error
But, when I tried doing the same with the esp32, it didn't work, and gave me this error:
network config: ('192.168.1.10', '255.255.255.0', '192.168.1.1', '192.168.1.1')
Traceback (most recent call last):
File "<stdin>", line 24, in <module>
File "<stdin>", line 19, in connect_socket
OSError: [Errno 113] ECONNABORTED
Well, thank you in advance! 🎉

Python3 Slack RTMClient in not working behind proxy

I am trying to create a simple Python bot for my project. Everything is working fine on my localhost, but the same code stops working behind the network firewall which needs environment proxy to be set.
from slack import RTMClient
proxy='http://XXXX:NNNN'
token='XXXX'
class Botso():
def __init__(self):
self.proxy=self.get_proxy()
self.rt= RTMClient(
token=token,
connect_method='rtm.start',
proxy=self.proxy
)
def get_proxy(self):
host=socket.gethostname()
if "internal" in host:
return None
elif "XXX" in host:
return proxy
#RTMClient.run_on(event="message")
def say_hello(**payload):
data = payload['data']
web_client = payload['web_client']
if 'text' in data and 'hii' in data['text']:
channel_id = data['channel']
thread_ts = data['ts']
user = data['user'] # This is not username but user ID (the format is either U*** or W***)
web_client.chat_postMessage(
channel=channel_id,
text=f"Hi <#{user}>!"
#thread_ts=thread_ts
)
if __name__ == '__main__':
botso=Botso()
botso.rt.start()
The error I am getting while initializing the RTMClient is
Traceback (most recent call last):
File "botso.py" , in <module>
botso.rt.start()
File "/usr/lib64/python3.6/http/client.py", line 974, in send
self.connect()
File "/usr/lib64/python3.6/http/client.py", line 1407, in connect
super().connect()
File "/usr/lib64/python3.6/http/client.py", line 950, in connect
self._tunnel()
File "/usr/lib64/python3.6/http/client.py", line 929, in _tunnel
message.strip()))
OSError: Tunnel connection failed: 403 Forbidden
I have other code in the same environment which uses the same proxy to send slack messages and works fine bu using request api.
params={
'token': self.slack_token,
'types': ['public_channel','private_channel']
}
slack_url='https://slack.com/api/conversations.list'
response = requests.get(url=slack_url,params=params,proxies=self.proxy).json()
How can we make the RTMClient work with proxy and Python3.
Couldn't find much help in slack API documents.

Issue when trying to send emails through Python

OS: MacCatalinva V10.15.3
Python: 3.7.7
PiP: 20.0.2
Hey,
I'm new to coding so I'm not sure what this really means.
I'm trying to send emails via Python through Gmail, I've set my account to accept "Less secure app access" and followed the steps in this guide, but all I get is the following:
`[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1076)
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/smtplib.py", line 354, in send
self.sock.sendall(s)
OSError: [Errno 9] Bad file descriptor
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/mymac/Desktop/Test2.py", line 34, in
server.quit()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/smtplib.py", line 984, in quit
res = self.docmd("quit")
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/smtplib.py", line 420, in docmd
self.putcmd(cmd, args)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/smtplib.py", line 367, in putcmd
self.send(str)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/smtplib.py", line 357, in send
raise SMTPServerDisconnected('Server not connected')
smtplib.SMTPServerDisconnected: Server not connected`
And this is my Code:
import smtplib
import ssl
sender_email = "myemailadress#gmail.com"
receiver_email = "myadress#hotmail.com"
message = """\
Subject: Hi there
This message is sent from Python."""
# Send email here
smtp_server = "smtp.gmail.com"
port = 587 # For starttls
sender_email = "myemailadress#gmail.com"
password = input("Type your password and press enter: ")
# Create a secure SSL context
context = ssl.create_default_context()
# Try to log in to server and send email
try:
server = smtplib.SMTP(smtp_server, port)
server.ehlo() # Can be omitted
server.starttls(context=context) # Secure the connection
server.ehlo() # Can be omitted
server.login(sender_email, password)
# TODO: Send email here
except Exception as e:
# Print any error messages to stdout
print(e)
finally:
server.quit()
1)After this line:
server.login(sender_email, password)
make sure to send the message you have it.
For that:
server.sendmail(sender_email,receiver_email,message)
that's it, I hope.

catch socket timeout error

i want to catch socket.timeout error, here is my code:
import socket
import sys
from time import sleep
print("Server Listening...")
IPparse = "localhost"
Portparse = 4444
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = (IPparse, Portparse)
serverSocket.settimeout(5)
serverSocket.bind(server_address)
serverSocket.listen(2)
(server, (ip,port)) = serverSocket.accept()
try:
data = server.recv(16).decode()
if data == "Hello":
print("Hallo Bro")
except socket.timeout as e:
print ("Timeout is over")
print (e)
but when i running that code. i got this error:
Server Listening...
Traceback (most recent call last):
File "C:\Users\astend\Desktop\TA\20180220 - Gabungan Gui - v.1\Socket\terima2.py", line 13, in <module>
(server, (ip,port)) = serverSocket.accept()
File "C:\Users\astend\AppData\Local\Programs\Python\Python36\lib\socket.py", line 205, in accept
fd, addr = self._accept()
socket.timeout: timed out
What key point am I missing here?
You need to do the accept() inside the try block.
Or else don't set the timeout on the listening socket, set it on the accepted sockets.

Python Socket Programming ConnectionRefusedError: [Errno 61] Connection refused

This is my code for the server program:
import socket
soket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
HOST = "localhost"
PORT = 8011
soket.bind((HOST,PORT))
print("%s:%d server başlatıldı." % (HOST,PORT))
print("Kullanıcı bekleniyor.")
soket.listen(2)
baglanti,adres = soket.accept()
print("Bir bağlantı kabul edildi.", adres)
baglanti.send("Hoşgeldiniz efendim , hoşgeldiniz.")
data = baglanti.recv(1024)
print(data)
soket.close()
And this is for the client:
import socket
clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientsocket.connect(("localhost", 8011))
clientsocket.send('hello')
Although I first start the server program and then the client program, I get this error:
Traceback (most recent call last):
File "/Users/Esat/Desktop/Python/Softwares/socketto copy.py", line 3, in <module>
clientsocket.connect(("localhost", 8011))
ConnectionRefusedError: [Errno 61] Connection refused
Instead of localhost, it is better to use LAN (local) IP. You can get your local IP by running ipconfig (in Windows) or ifconfig (in GNU/Linux or Mac OS). Your local IP should be something like 192.168.1.x.

Resources