Python Threads Run When Created, Not When run() is Called - python-2.7

In my python program (2.7), I attempt to create a thread but it instantly starts when it is created, not when the start() and then the run() attributes are called. Help would be great.
Here is my (server) code:
import sys
import socket
import threading
global connections
connections = []
def srcv(s, conn, data):
while True:
print "Recieving"
#Recieve Strings From Each Connection
for i, n in enumerate(connections):
data.append([connections[1], i.recv(4096)])
#Send String To Each Connection
print "Sending"
for i, n in enumerate(connections):
i.send("{0}: {1}".format(data[n][0], data[n][1]))
def listn(s, conn, data):
s.listen(10)
print "Listening For Connection"
while True:
obj, addr = s.accept()
connections.append([obj, addr])
def start_server():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
conn = []
data = []
s.bind(("localhost", 12345))
print "Creating Listening Thread"
listen = threading.Thread(target=listn(s,conn,data))
print "Preparing Listening Thread"
listen.start()
print "Starting Listening Thread"
listen.run()
print "Creating Send/Receive Thread"
sandr = threading.Thread(target=srcv(s, conn, data))
print "Preparing Send/Receive Thread"
sandr.start()
print "Connections Now Acceptable"
sandr.run()
if __name__ == '__main__':
sys.exit(start_server())
Please let me know if my code seems clunky/disorganized, I am somewhat new to programming in general.
EDIT:
Another problem I encountered is that I cannot run both of the threads, as when one starts, the other can not be. Why is that, and how can I fix it?

You need to use put the arguments in args= so that the function is not called before listen.start():
listen = threading.Thread(target=listn, args=(s,conn,data))
Not
listen = threading.Thread(target=listn(s,conn,data))
Also you shouldn't call .run(), .start() does that internally on the newly started thread. Therun method is there so that subclasses of Thread can override it.

Related

Python 2.7 ignoring if not statement?

I'm creating a simple socket chatting application and I tried to make something that handles somebody terminating the client connected to the server, but it seems to ignore it and I get the connection forcibly closed by the remote host exception.
Here's some of the code
clients = []
class client(Thread):
def __init__(self, socket, address):
Thread.__init__(self)
self.sock = socket
self.addr = address
self.start()
def run(self):
while 1:
msg = self.sock.recv(1024).decode()
#This if not statement is ignored
if not msg:
clients.remove(socket)
print str(adress[0]) + ":" + str(adress[1]) + " disconnected"
quitm = str(adress[0]) + ":" + str(adress[1]) + " disconnected"
for client in clients:
client.send(quitm.encode())
socket.close()
break
print msg
for client in clients:
client.send(msg.encode())
I've been searching up for some solutions but haven't found any. Any help is appreciated!!!
If the thing at the other end closes the connection normally, that is indicated by recv() returning zero bytes. However, if the thing at the other end terminates without closing the connection, that is considered an abnormal situation which indicated by recv() raising an exception. You need to use a try/catch block to handle that exception.

How do I loop ports to scan?

I have this problem with a portscanner which keeps hanging at scanning port 1. How can I solve this problem?
#! /usr/bin/env python
import socket
import subprocess
from datetime import datetime
#Clear the screen
subprocess.call('clear', shell=True)
def portscan():
server = raw_input("Enter the server to scan: ")
serverIP = socket.gethostbyname(server)
# Printing banner with information about host
print "[+] Host: {} [+]\nIP Address: {}\n".format(server, serverIP)
print "[!] Please wait, scanning for open services...\n"
#Time when scan started.
t1 = datetime.now()
try:
for port in range(1, 1024):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((serverIP, port))
if result == 0:
print "[+] Port {}: Status:OPEN\n".format(result)
sock.close()
except socket.gaierror:
print "Hostname could not be resolved, Exiting...\n"
sys.exit()
except socket.error:
print "Couldn\'t connect to server, Exiting\n"
sys.exit()
#Checking time again
t2 = datetime.now()
#Calculate duration of scan
totaltime = t2 - t1
print "Scan completed, duration: {}\n".format(totaltime)
What happens when i run it i give it a hostname and resolve it to a IP
Address but whenever the scan starts it keeps scanning port 1 as i saw
in Wireshark
I think that you maybe need a timeout.
Eventually, your sock.connect_ex( ), will to raise an exception socket.error: [Errno 110] Connection timed out, as you can read more about it, in this answer.
But the default timeout could be 120 seconds, and maybe you don't want to wait so much. So, you can set your own timeout, like that:
try:
for port in range(1, 1024):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(10) #timeout set for wait up 10 seconds.
result = sock.connect_ex((serverIP, port))
sock.settimeout(None)
To know why to use sock.settimeout(None), and see another ways of setting timeout, you can read this discussion.
I'm not sure if it was what you're looking for, but I hope it may help.

Is there any way to stop a background process when you enter pdb?

So, I have some code like this:
class ProgressProc(multiprocessing.Process):
def __init__(self):
multiprocessing.Process.__init__(self)
def run(self):
while True:
markProgress()
time.sleep(10)
progressProc = ProgressProc()
progressProc.start()
doSomething()
progressProc.terminate()
The problem is, if I do pdb.set_trace() inside the doSomething() function, the ProgressProc process keeps going. It keeps printing stuff to the console while the pdb prompt is active. What I would like is to have some way for ProgressProc to check if the main thread (really, any other thread) is suspended in pdb and then I can skip markProgress().
There's sys.gettrace(), but that only works for the thread that did the pdb.set_trace() and I can't figure out how to call it on a different thread than the one I'm in. What else can I do? Are there any signals I can catch? I could have my main method replace pdb.set_trace to call some multiprocessing.Event first. Is there any cleaner way?
ETA: This is also for a python gdb command.
Debugging with multiple threads or processes is currently not possible with Pdb. However, I hope the following can help you.
This solution suspends the main thread with Pdb and then sends a signal to the other process where Rpdb is started.
Open a socket in run. Make sure to set the timeout to 0. When the process receives a signal, start Rpdb with rpdb.set_trace().
signal = 'break'
address = ('localhost', 6000)
def run(self):
listener = Listener(address=address)
listener._listener._socket.settimeout(0)
recvd = False
while True:
markProgress()
if not recvd:
try:
conn = listener.accept()
msg = conn.recv()
if msg == signal:
recvd = True
rpdb.set_trace()
except:
pass
time.sleep(2)
Do set_trace() inside doSomething() like before, then connect to the socket and send the signal.
def doSomething():
pdb.set_trace()
conn = Client(address)
conn.send(signal)
conn.close()
for x in range(100):
time.sleep(1)
sys.__stdout__.write("doSomething: " + str(x) + "\n")
Now you can start your program. After the signal is sent, you should get the output pdb is running on 127.0.0.1:4444. Now open a second terminal and connect to Rpdb with nc localhost 4444.
This only works with two processes/threads. If you want to work with more, you could try starting Rpdb with a different port for each process, like this: rpdb.Rpdb(port=12345)
You may have to change all your prints to sys.__stdout__.write, because Rpdb changes stdout.

My Threading Chat Server isn't work in parallel . Python 2.7

Can someone tell me how to make my code work in parallel , that the client see immediately what other sent and if someone joined the chat . (the code isn't finished because I stopped when I saw the function "receive" and "startconnection" doesn't work in the same time)
the receive function is getting data from the client and sending it to everyone except himself . the startconnection function start connection with clients.
I need that new will client always be able to connect the server and send and get data from other clients.
The Code:
import socket
import threading
import time
add=[]
d=[]
i=0
def startconnection():
time.sleep(0.6)
server_socket.listen(1)
(client_socket,client_address)=server_socket.accept()
print "new client has connected"
if i!=0:
sendall("new client connected",i)
global d
global add
global i
add=add+[client_address]
d=d+[client_socket]
i+=1
x=True
def receive(tmp):
time.sleep(0.6)
global x
global i
global d
print "I am here again working with client number: %d ,the numbers of
connected clients are : %d" %(tmp,i)
data=d[tmp].recv(1024)
if data!= "":
print "needs to send everyone exept the sender this data: %s" %
(data)
sendall(data,findplace(d[tmp]))
print "Finish working with client"
def sendall(text,nottosend):
print "got to sendall"
global i
global d
tp=0
while tp<i:
if tp!=nottosend:
d[tp].send(text)
tp+=1
def run():
global i
thread = threading.Thread(target=startconnection())
thread.daemon = True
thread.start()
time.sleep(0.6)
b=0
while i != 0 and b<=i-1:
time.sleep(0.6)
thread = threading.Thread(target=receive(b)).start()
b+= 1
def findplace(client_socket):
global d
i=0
while i<len(d):
if client_socket==d[i]:
return i
else:
i+=1
print "!!!!!!!!!!!Eror in findplace!!!!!!!!!!!"
return -1
if __name__ == '__main__':
server_socket = socket.socket()
server_socket.bind(('127.0.0.1', 231))
while x:
thread = threading.Thread(target=run())
thread.daemon = True
thread.start()

python daemon signal handling: cannot override default

I'm writing a python daemon using the daemon module. I want it to respond to SIGALRM, SIGHUP, SIGUSR1 etc to perform daemon control functions.
I find that the signal handler gets called OK, however the daemon terminates when I expect it to continue running. How do I get the handler to run without terminating the daemon?
I've tried registering handlers both with signal.signal and with context.signal_map. The behaviour is the same in both cases.
Proto handler looks like this:
def myhandler(signum, frame):
logger.info("Received Signal: %s at frame: %s" % (signum, frame))
Signal registration looks like this
context.signal_map = {
signal.SIGHUP: myhandler,
signal.SIGUSR1: myhandler,
signal.SIGUSR2: myhandler,
}
This piece of code works for me:
import signal
import daemon
import time
def do_main_program():
while True:
with open("/tmp/current_time.txt", "w") as f:
f.write("The time is now " + time.ctime())
time.sleep(5)
def reload_program_config(signum, frame):
with open("/tmp/reload.txt", "w") as f:
f.write("The time is now " + time.ctime())
return None
def run():
context = daemon.DaemonContext()
context.signal_map = {
signal.SIGHUP: 'terminate',
signal.SIGUSR1: reload_program_config,
}
with context:
do_main_program()
if __name__ == "__main__":
run()