I wanted to create a python script to stress test my servers.
So I created this basic UDP flooder and I think I have it working correctly.
My question is how would I go about adding multi-threading to this?
I read a manual on Python threading but didn't understand how to actually
implement it into my script.
import socket
import random
print "Target:",
ipaddr = raw_input()
sent = 1
bytes = random._urandom(10000)
port = 1
while sent > 0:
print "Test Started On", ipaddr, "|", sent, "Packets Sent. Press Ctrl+C To Stop."
sent += 1
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.sendto(bytes,(ipaddr,port))
port = random.randint(1, 65500)
raw_input()
If you extract the business part of your application into a function like:
def do_the_flooding():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.sendto(bytes,(ipaddr,port))
You can then call it in a thread:
import threading
t = threading.Thread(target=do_the_flooding)
t.start()
Related
I'm new to socket programming in Python and I'm trying to write a chatroom application, but I have a problem which is it each client should press enter in order to receive messages from other clients.
#my client side code
import socket
import sys
client_sock = socket.socket()
port = int(sys.argv[1])
client_sock.connect(('127.0.0.1', port))
print("Connected to server. start sending messages")
while True:
sending_message = input('> ')
if sending_message:
client_sock.send(sending_message.encode())
receiving_message = client_sock.recv(1024)
if receiving_message:
print(receiving_message.decode())
input pauses your program. Thus, either you can't use input blindly, or you have to use threads. Using threads is easier than the alternative (using select to figure out what to do next). Have one thread for input and sending, one thread for receiving and printing.
Here's a trivial rewrite of your code:
import threading
import socket
import sys
client_sock = socket.socket()
port = int(sys.argv[1])
client_sock.connect(('127.0.0.1', port))
print("Connected to server. start sending messages")
def sender():
while True:
sending_message = input('> ')
if sending_message:
client_sock.send(sending_message.encode())
def receiver():
while True:
receiving_message = client_sock.recv(1024)
if receiving_message:
print(receiving_message.decode())
sender_thread = threading.Thread(target=sender)
receiver_thread = threading.Thread(target=receiver)
sender_thread.start()
receiver_thread.start()
sender_thread.join()
receiver_thread.join()
So I am new to python and I'm trying to learn some socket programming and the following script, when ran and connected to the server via telnet, returns me something like "hheelllloo wwoorrlldd" instead of letting me write "hello world" and then send the data. I've looked online and I've already tried to change the localecho setting in telnet and that didn't work either.
The servers script is:
import socket
import sys
import threading
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('127.0.0.1', 10000))
sock.listen(1)
connections = []
def handler(c, a):
global connections
while True:
data = c.recv(1024)
for connection in connections:
connection.send(bytes(data))
if not data:
connections.remove(c)
c.close()
break
while True:
c, a = sock.accept()
conn_thread = threading.Thread(target = handler, args = (c, a))
conn_thread.daemon = True
conn_thread.start()
connections.append(c)
The code when ran should return the sender the text he sent. I think mine does it character by character, without pressing enter to send and I don't know why. I might be wrong though.
Also, I'm running Windows 10, if this matters.
I am trying to create a port scanner in Python. I got the scanner going but it takes forty five minutes to print results. I started to institute threading however I can't figure out how to put different ranges into the script. I started to go to creating a global variable and try to pass that along in each thread. Unfortunately it's not working correctly and I am getting an invalid syntax error. Below is the code.
import socket
import os
import sys
from threading import Thread
server = raw_input("Please enter a server name ")
def portConnect():
global num
try:
serv_ip = socket.gethostbyname(server) # connects to server through try
print "Please wait, scanning remote host", serv_ip
for port in range(num):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connect = sock.connect_ex((serv_ip, port))
if connect == 0:
print "Port {}: Open".format(port)
sock.close()
except socket.gaierror:
print """
I can't find that server, idiot! Try again
"""
sys.exit()
for i in range(1):
t = Thread(target=portConnect,(num=100))
t.start()
What am I doing wrong?
Thread expects args= as tuple and it sends it as arguments to function
This way you send 100 as first argument (num) to portConnect()
def portConnect(num):
print(num)
# code
t = Thread(target=portConnect, args=(100,) )
To send range you need two arguments
def portConnect(from_, to_):
print(from_, to_)
for port in range(from_, to_):
# ...
size = 20
for i in range(1, 100, size):
t = Thread(target=portConnect, args=(i, i+size))
t.start()
BTW: module scapy lets you send single packet so it is used for portscanning, sniffing, etc.
You can do more with special tools like nmap (GUI wrapper: Zenmap) or Kali Linux
You may try to use nmap in Python: python-nmap : nmap from python
you can solve this really easily using nmap.
nmap -p- <some_host>
I have recently starting learning network programming with python. Here is a simple server I tried to write:
import socket
def server():
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(('127.0.0.1', 1024))
while True:
data, address = sock.recvfrom(65535)
text = data.decode('ascii')
print('the client from {0} sent: "{1}"'.format(address, text))
if text is '0': break
I wanted the server to wait till it is getting packets from the server, but when I run it, it will close instantly.
what did I do wrong?
You're not actually calling server().
Add this after the function definition:
if __name__ == '__main__':
server()
This is my code:
socketcheck.py
import time
import subprocess
subprocess.Popen(["python", "server.py"])
for i in range(10):
time.sleep(2)
print i
def print_from_server(data):
print data
server.py
import socket
from socketcheck import print_from_server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('localhost',3005))
client_connected = 1
while 1:
s.listen(1)
conn, addr = s.accept()
data = conn.recv(1024)
if data:
client_connected = 0
else: break
if client_connected == 0:
print 'data received'
print_from_server(data)
client_connected = 1
conn.sendall(data)
client.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('localhost',3005))
s.sendall('Hello, world')
data = s.recv(1024)
#s.close()
print 'Received', repr(data)
What I am trying to do here is, run socketcheck.py which runs server.py in background and listens for a client connection. So whatever data the client sends, I want to pass it on to socketcheck.py. Is this valid? If so, then how do I achieve it?
Now when I try and run socketcheck.py, the for loop is running indefinitely.
Thanks :)
EDIT:
This initially I tried as a single program, but until the client gets connected, the rest of the program doesn't execute(blocking), with the setblocking(0) the program flow wouldn't stop but when the client connects to server it doesn't print(do anything). The server code looked something like this:
import socket
from socketcheck import print_from_server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('localhost',3005))
s.setblocking(0)
while 1:
try:
s.listen(1)
conn, addr = s.accept()
conn.setblocking(0)
data = conn.recv(1024)
if not data: break
print 'data received'
conn.sendall(data)
except:
print 'non blocking'
print 'the lengthy program continues from here'
The reason why your program crashes your computer is simple:
You have a while loop which calls print_from_server(data), and each time it calls it, a new subprocess gets created via subprocess.Popen(["python", "server.py"]).
The reason for creating a new popen each time is a bit more complicated: You open a new server.py program in socketcheck.py. If this new server.py program calls print_from_server(data), this is the first time print_from_server(data) gets called (for the new server.py program). So the global commands (such as popen) are executed, since they are always executed once.
The number of processes running will explode quickly and you computer crashes.
One additional remark: You cannot print to console with a print command in a subprocess, since there is no console attached to that subprocess, you can only print to file. If you do that, you'll see that this output explodes quickly from all the processes.
Put socketcheck.py and server.py into one program and everything works fine, or explain why you need two programs.
The functionality can be easily achieved with multithreading :)