I am using python3 asyncio_socks_server library to run a socks proxy, my program is supposed to run a socks proxy in a thread and an HTTP server on another thread then continue execution.
Here is my socks_proxy.py:
import socket
from asyncio_socks_server.__version__ import __version__
from asyncio_socks_server.app import SocksServer
class SocksProxy:
def __init__(self, local_ip, port):
args = []
config_args = {
"LISTEN_HOST": local_ip,
"LISTEN_PORT": port,
"AUTH_METHOD": 0,
"ACCESS_LOG": 0,
"DEBUG": 1,
"STRICT": 0,
}
app = SocksServer(
config=None,
env_prefix="AIOSS_",
**{k: v for k, v in config_args.items() if v is not None},
)
app.run()
def startSocksProxy(local_ip, port):
s = SocksProxy(local_ip, port)
main.py:
import threading
from modules.util.socks_proxy import startSocksProxy
from modules.logger.logger import Logger
if "__main__" == __name__:
logger = Logger()
remoteLog = threading.Thread(target=startLoggerServer)
remoteLog.start()
socksProxy = threading.Thread(target=startSocksProxy, args=(LOCAL_IP, 7000))
socksProxy.start()
The HTTP server starts fine, however, I am getting the following error:
Exception in thread Thread-2:
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner
self.run()
File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "j:\WormScanner\modules\util\socks_proxy.py", line 35, in startSocksProxy
s = SocksProxy(local_ip, port)
File "j:\WormScanner\modules\util\socks_proxy.py", line 26, in __init__
app = SocksServer(
File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\site-packages\asyncio_socks_server\app.py", line 23, in __init__
self.loop = asyncio.get_event_loop()
File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\asyncio\events.py", line 639, in get_event_loop
raise RuntimeError('There is no current event loop in thread %r.'
RuntimeError: There is no current event loop in thread 'Thread-2'.
and the socks proxy doesn't start.
To anyone who ever faces this problem, it worked fine when I used multiprocessing:
if "__main__" == __name__:
multiprocessing.freeze_support()
remoteLog = multiprocessing.Process(target=startLoggerServer)
remoteLog.start()
socksProxy = multiprocessing.Process(target=startSocksProxy, args=(LOCAL_IP, 7000))
socksProxy.start()
Related
I am trying to run a discord bot and flask server in one file, I thought it worked but the flask server does nothing so I checked with debug options True, now I get this error:
$ python main.py
Traceback (most recent call last):
File "main.py", line 262, in <module>
run()
File "main.py", line 260, in run
* Serving Flask app 'main'
* Debug mode: on
Tools().discordbot()
File "main.py", line 204, in discordbot
threading.Thread(target=loopy.run_forever).start()
NameError: name 'loopy' is not defined
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
* Running on all addresses (0.0.0.0)
* Running on http://127.0.0.1:8080
* Running on http://198.54.114.12:8080
Press CTRL+C to quit
Exception in thread Thread-1:
Traceback (most recent call last):
File "/opt/alt/python38/lib64/python3.8/threading.py", line 932, in _bootstrap_inner
self.run()
File "/opt/alt/python38/lib64/python3.8/threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "main.py", line 213, in __init__
self.RunApi()
File "main.py", line 254, in RunApi
app.run(host="0.0.0.0",port=8080, debug=True)
File "/home/darkehld/virtualenv/verify.darkys.wtf/3.8/lib/python3.8/site-packages/flask/app.py", line 1188, in run
run_simple(t.cast(str, host), port, self, **options)
File "/home/darkehld/virtualenv/verify.darkys.wtf/3.8/lib/python3.8/site-packages/werkzeug/serving.py", line 1090, in run_simple
run_with_reloader(
File "/home/darkehld/virtualenv/verify.darkys.wtf/3.8/lib/python3.8/site-packages/werkzeug/_reloader.py", line 427, in run_with_reloader
signal.signal(signal.SIGTERM, lambda *args: sys.exit(0))
File "/opt/alt/python38/lib64/python3.8/signal.py", line 47, in signal
handler = _signal.signal(_enum_to_int(signalnum), _enum_to_int(handler))
ValueError: signal only works in main thread
my contains this to start the discord bot which works fine:
myLoop.start()
threading.Thread(target=loopy.run_forever).start()
loop = asyncio.get_event_loop()
loop.create_task(self.bot.start(self.BotToken))
threading.Thread(target=loop.run_forever).start()
but the flask server does not work, the run command I use for it is this:
class ApiBot:
def __init__(self) -> None:
self.RunApi()
def RunApi(self):
app = Flask(__name__)
#app.route('/auth')
def auth():
code = request.args.get("code")
if (code != None):
if AntiSql(code) == True:
return jsonify({"error":"1004"})
discord = Discordx()
res = discord.ExchangeCode(code)
try:
access_token = res['access_token']
refresh_token = res['refresh_token']
info = discord.GetInfo(access_token)
username = info['username']
avatar = info['avatar']
userid = info['id']
except:
return jsonify({"error":"1005"})
data = {
"access_token": access_token,
"refresh_token": refresh_token,
"username":username,
"avatar":avatar,
"userid":userid,
"ip":request.remote_addr
}
if Memberdb.CheckIfUserIsInDb(data) == False:
Memberdb.AddNewMember(data)
ListToSend.append(data)
return "<script>window.close();</script>"
else:
return jsonify({"error":"1002"})
app.run(host="0.0.0.0",port=8080, debug=True)
def run():
threading.Thread(target=ApiBot).start()
can someone help me? thanks in advance
So, I have coded a Discord Bot, but I want to run it in a thread, because I need pyramid for a webhook with GitHub. I will run it side by side, because the bot should write a message, when I push a update for my website hosted by GitHub Pages.
I got the pyramid server running but the bot wont start and when I try to run the bot normally, It runs quite nice.
The errors I got are:
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner
self.run()
File "/usr/lib/python3.8/threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "/home/nikurasu/PycharmProjects/pyramidtest/test2.py", line 35, in discordthread
client = MyClient()
File "/home/nikurasu/PycharmProjects/pyramidtest/venv/lib/python3.8/site-packages/discord/client.py", line 206, in __init__
self.loop = asyncio.get_event_loop() if loop is None else loop
File "/usr/lib/python3.8/asyncio/events.py", line 639, in get_event_loop
raise RuntimeError('There is no current event loop in thread %r.'
RuntimeError: There is no current event loop in thread 'Thread-1'.
I simplified the code to exclude other shitcode written by me, but even when I use that simple code, the bot do not want to run:
import threading
import discord
from wsgiref.simple_server import make_server
from pyramid.config import Configurator
from pyramid.response import Response
def hello_word(request):
return Response('Hello World')
def hello_jonas(request):
return Response('<b>Hello, Jonas</b>')
def pyramidthread():
with Configurator() as config:
config.add_route('hello', '/')
config.add_view(hello_word, route_name='hello')
config.add_route('jonas', '/jonas')
config.add_view(hello_jonas, route_name='jonas')
app = config.make_wsgi_app()
server = make_server('0.0.0.0', 6543, app)
server.serve_forever()
def discordthread():
token = 'nothing'
class MyClient(discord.Client):
async def on_ready(self):
print('Eingeloggt als', self.user)
print("Izuna versucht zu starten")
client = MyClient()
client.run(token)
t1 = threading.Thread(target=discordthread)
t2 = threading.Thread(target=pyramidthread)
t1.start()
t2.start()
I hope someone here can help me^^
I was trying to write a chat for a local network (the same with one represented in this tutorial). And when executing the code there have occured some mistakes. First of all,when one of the clients stops it's work with ctrl+c combination the command line of this client throws this exception
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Users\Samsung-PC\AppData\Local\Programs\Python\Python35-
32\lib\threading.py", line 914, in _bootstrap_inner
self.run()
File "C:\Users\Samsung-PC\AppData\Local\Programs\Python\Python35-
32\lib\threading.py", line 862, in run
self._target(*self._args, **self._kwargs)
File "chat.py", line 39, in send_message
self.s.send(bytes(input(""),'utf-8'))
EOFError
and the client still works whithout exiting the program. The work of this client stops only when another client connects to the server. Then,another problem is that server crashes with that exception when one of the clients closes his widow with chat.
Exception in thread Thread-2:
Traceback (most recent call last):
File "C:\Users\Samsung-PC\AppData\Local\Programs\Python\Python35-
32\lib\threading.py", line 914, in _bootstrap_inner
self.run()
File "C:\Users\Samsung-PC\AppData\Local\Programs\Python\Python35-
32\lib\threading.py", line 862, in run
self._target(*self._args, **self._kwargs)
File "chat.py", line 14, in handler
data=c.recv(1024)
ConnectionResetError: [WinError 10054]
And here is the code
import socket
import threading
import sys
class Server:
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
connections = []
def __init__(self):
self.s.bind(('192.168.56.1',9090))
self.s.listen(1)
def handler(self,c,a):
while True:
data=c.recv(1024)
for connection in self.connections:
connection.send(data)
if not data:
self.connections.remove(c)
c.close()
print(str(a[0])+':'+str(a[1]),'disconnected')
break
def run(self):
while True:
c,a =self.s.accept()
cThread=threading.Thread(target=self.handler,args=(c,a))
cThread.daemon=True
cThread.start()
self.connections.append(c)
print(str(a[0])+':'+str(a[1]),'connected')
class Client:
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
def send_message(self):
while True:
self.s.send(bytes(input(""),'utf-8'))
def __init__(self,addr):
self.s.connect((addr,9090))
iThread=threading.Thread(target=self.send_message)
iThread.daemon=True
iThread.start()
while True:
data=self.s.recv(1024)
if not data:
break
print(str(data,'utf-8'))
if (len(sys.argv) > 1):
client=Client(sys.argv[1])
else:
server=Server()
server.run()
How can I change this code to make it work on windows 10 without such mistakes (or any other mistakes))?
I just simply use the tornado application together with threading as the following code:
def MakeApp():
return tornado.web.Application([(r"/websocket", EchoWebSocket), ])
def run_tornado_websocket():
app = MakeApp()
http_server = tornado.httpserver.HTTPServer(app, ssl_options={
"certfile": os.path.join(os.path.abspath("."), "server.crt"),
"keyfile": os.path.join(os.path.abspath("."), "server_no_passwd.key"),
})
http_server.listen(options.port)
tornado.ioloop.IOLoop.current().start()
if __name__ == '__main__':
threads = []
t = threading.Thread(target=run_tornado_websocket, args=())
threads.append(t)
for t in threads:
t.start()
It works fine on python3.5.But it fails on python3.6 and the lasted tornado.It gets the error:
Exception in thread Thread-1:
Traceback (most recent call last):
File "D:\python3\lib\threading.py", line 916, in _bootstrap_inner
self.run()
File "D:\python3\lib\threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "D:\ssl\ws_server.py", line 49, in run_tornado_websocket
http_server.listen(options.port)
File "D:\python3\lib\site-packages\tornado\tcpserver.py", line 145, in listen
self.add_sockets(sockets)
File "D:\python3\lib\site-packages\tornado\tcpserver.py", line 159, in add_sockets
sock, self._handle_connection)
File "D:\python3\lib\site-packages\tornado\netutil.py", line 219, in add_accept_handler
io_loop = IOLoop.current()
File "D:\python3\lib\site-packages\tornado\ioloop.py", line 282, in current
loop = asyncio.get_event_loop()
File "D:\python3\lib\asyncio\events.py", line 694, in get_event_loop
return get_event_loop_policy().get_event_loop()
File "D:\python3\lib\asyncio\events.py", line 602, in get_event_loop
% threading.current_thread().name)
RuntimeError: There is no current event loop in thread 'Thread-1'.
I think there are some changes in IOLOOP in python3.6.But I don't know how to fix this and really want to know the reason.
Starting in Tornado 5.0, the asyncio event loop is used by default. asyncio has some extra restrictions because starting event loops on threads other than the main thread is an uncommon pattern and is often a mistake. You must tell asyncio that you want to use an event loop in your new thread with asyncio.set_event_loop(asyncio.new_event_loop()), or use asyncio.set_event_loop_policy(tornado.platform.asyncio.AnyThreadEventLoopPolicy()) to disable this restriction.
Why do I get an error while trying to implement LoopingCall function calling AMP commands?
from twisted.protocols.amp import AMP
from twisted.python.log import startLogging, err
from twisted.internet.task import LoopingCall
from twisted.internet import reactor
from sys import stdout
import commands
startLogging(stdout)
class MyAMP:
def __init__(self, host, port):
destination = TCP4ClientEndpoint(reactor, host, port)
self.protocol = AMP()
self.d = connectProtocol(destination, self.protocol)
def say(self):
return self.protocol.callRemote(commands.Say,
phrase='Hello world')
def loop(myamp):
myamp.say()
def main(host, port):
myamp = MyAMP(host, port)
lc = LoopingCall(loop, myamp=myamp)
lc.start(4.0)
reactor.run()
main('127.0.0.1', 12345)
Error while calling myamp.say() within loop:
2013-08-16 12:28:58-0400 [-] Starting factory <twisted.internet.endpoints.OneShotFactory instance at 0x92273ec>
2013-08-16 12:28:58-0400 [-] Unhandled error in Deferred:
2013-08-16 12:28:58-0400 [-] Unhandled Error
Traceback (most recent call last):
File "lib/client.py", line 35, in <module>
main('127.0.0.1', 12345)
File "lib/client.py", line 32, in main
lc.start(4.0)
File "/usr/local/lib/python2.7/site-packages/twisted/internet/task.py", line 173, in start
self()
File "/usr/local/lib/python2.7/site-packages/twisted/internet/task.py", line 218, in __call__
d = defer.maybeDeferred(self.f, *self.a, **self.kw)
--- <exception caught here> ---
File "/usr/local/lib/python2.7/site-packages/twisted/internet/defer.py", line 137, in maybeDeferred
result = f(*args, **kw)
File "lib/client.py", line 26, in loop
myamp.say()
File "lib/client.py", line 22, in say
phrase='Hello world')
File "/usr/local/lib/python2.7/site-packages/twisted/protocols/amp.py", line 821, in callRemote
return co._doCommand(self)
File "/usr/local/lib/python2.7/site-packages/twisted/protocols/amp.py", line 1778, in _doCommand
self.requiresAnswer)
File "/usr/local/lib/python2.7/site-packages/twisted/protocols/amp.py", line 752, in _sendBoxCommand
box._sendTo(self.boxSender)
File "/usr/local/lib/python2.7/site-packages/twisted/protocols/amp.py", line 577, in _sendTo
proto.sendBox(self)
exceptions.AttributeError: 'NoneType' object has no attribute 'sendBox'
2013-08-16 12:28:58-0400 [Uninitialized] AMP connection established (HOST:IPv4Address(TCP, '127.0.0.1', 50457) PEER:IPv4Address(TCP, '127.0.0.1', 12345))
You're trying to callRemote before the connection is established. A LoopingCall will, by default, immediately run its function when you start it. Instead of doing lc.start(4.0), do lc.start(4.0, now=False). This will wait four second before the first call.
In the normal environment, where the network connection is rock stable, the way of #habnabit will be working, but in the real world, the connection latency can not be estimated as you expect. The better solution for this problem, the looping call must be executed after the amp client is connected like this.
from twisted.protocols.amp import AMP
from twisted.python.log import startLogging, err
from twisted.internet.task import LoopingCall
from twisted.internet import reactor, endpoints
from sys import stdout
import commands
startLogging(stdout)
class MyAMP:
def __init__(self, host, port):
destination = endpoints.TCP4ClientEndpoint(reactor, host, port)
self.protocol = AMP()
self.d = endpoints.connectProtocol(destination, self.protocol)
def loop (proto, ) :
return proto.callRemote(commands.get_user, key='Hello world')
def main(host, port):
def _cb_connected (proto, ) :
lc = LoopingCall(loop, proto, )
lc.start(4.0)
return
myamp = MyAMP(host, port)
myamp.d.addCallback(_cb_connected, )
reactor.run()
return
main('127.0.0.1', 12345, )