Passing received data to "input" function in python - python

Okay, so I createda socket server in python and I want when someone connects to it to run an application on the sever but which is user controlled. I'll try to explain better with the code.
#!/usr/bin/python
import socket
import select
import os
from time import sleep
class SocketServer:
""" Simple socket server that listens to one single client. """
def __init__(self, host = '0.0.0.0', port = 2010):
""" Initialize the server with a host and port to listen to. """
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.host = host
self.port = port
self.sock.bind((host, port))
self.sock.listen(1)
def close(self):
""" Close the server socket. """
print('Closing server socket (host {}, port {})'.format(self.host, self.port))
if self.sock:
self.sock.close()
self.sock = None
def run_server(self):
""" Accept and handle an incoming connection. """
print('Starting socket server (host {}, port {})'.format(self.host, self.port))
client_sock, client_addr = self.sock.accept()
print('Client {} connected'.format(client_addr))
stop = False
while not stop:
if client_sock:
# Check if the client is still connected and if data is available:
os.system("python vuln.py")
# try:
# rdy_read, rdy_write, sock_err = select.select([client_sock,], [], [])
# except select.error:
# print('Select() failed on socket with {}'.format(client_addr))
# return 1
if len(rdy_read) > 0:
read_data = client_sock.recv(255)
if len(read_data) == 0:
print('{} closed the socket.'.format(client_addr))
stop = True
else:
print('>>> Received: {}'.format(read_data.rstrip()))
if read_data.rstrip() == 'quit':
stop = True
else:
client_sock.send(read_data)
else:
print("No client is connected, SocketServer can't receive data")
stop = True
# Close socket
print('Closing connection with {}'.format(client_addr))
client_sock.close()
return 0
def main():
server = SocketServer()
while (True):
server.run_server()
print 'Exiting'
if __name__ == "__main__":
main()
This is my socket server, which always runs and cand establish multiple connections.
print("Please tell me what's your age")
age = input('> ')
sleep(1)
print("Damn man, sometimes I wish I was %s" % age)
sleep(1)
and this is the app which I want to run on the server and let the user who connects with netcat for example see the same prompt and have the same functionality but on the server.

Related

Can't tell if python server and client are interacting with each other

Have a client socket here that starts and connects but the receive function never runs or at least doesn't print. I get no errors in the console
import socket
from threading import Thread
MAX_BUFFER_SIZE = 4096
class ClientServer(Thread):
def __init__(self, HOST = "localhost", PORT = 8000):
print("Client Server started w/ new threads...")
Thread.__init__(self)
self.HOST = HOST
self.PORT = PORT
self.socket = None
def receive_from_Server(self):
print('Time to receive from Server.....')
result_bytes = self.socket.recv(MAX_BUFFER_SIZE)
result_string = result_bytes.decode("utf8")
print("Result from server is {}".format(result_string))
def start_server(self):
# Creates TCP socket
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Re-uses socket
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# Binds socket to host and port
self.socket.bind(("localhost", 8000))
def connect_server(self):
while True:
threads = []
# Become a server socket
print("Waiting for connections from TCP clients")
self.socket.listen(5)
# Starts connection
(clientSocket, client_address) = self.socket.accept()
newthread = ClientServer()
newthread.start()
threads.append(newthread)
for t in threads:
t.join()
cs = ClientServer()
cs.start_server()
cs.connect_server()
cs.receive_from_Server()
my client code here runs but again print doesn't print after I run this program and enter whatever message besides 'exit' as well as 'exit' not closing the client as well.
import socket
host = "localhost"
port = 8000
BUFFER_SIZE = 4096
MESSAGE = input("Client: Enter message and hit enter or 'exit' to end ")
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((host, port))
while MESSAGE != 'exit':
client.send(MESSAGE.encode("utf8"))
data = client.recv(BUFFER_SIZE)
print("Server received data:" + data)
MESSAGE = input("Client: Enter more or 'exit' to end ")
client.close()

Python Chat Room "ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host"

I'm trying to make a chat room that works on localhost with threading and socket. Here is the code:
# Server side
import threading
import socket
host = 'localhost'
port = 11298
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((host, port))
server.listen()
clients = []
nicks = []
def broadcast(msg):
for client in clients:
client.send(msg)
def handle(client):
while True:
try:
msg = client.recv(1024)
broadcast(msg)
except:
index = clients.index(client)
clients.remove(client)
client.close()
nick = nicks[index]
broadcast(f'{nick} has left.'.encode('utf-8'))
nicks.remove(nick)
break
def recv():
while True:
print('The chat room is online ...')
client, address = server.accept()
print(f'You are connected to {str(address)}')
client.send('nick'.encode('utf-8'))
nick = client.recv(1024)
nicks.append(nick)
clients.append(client)
broadcast(f'{nick} has joined.'.encode('utf-8'))
client.send('You have been connected!'.encode('utf-8'))
thread = threading.Thread(target = handle(), args = (client))
thread.start()
if __name__ == "__main__":
recv()
# Client side
import threading
import socket
nick = input('Choose a nickname: ')
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('localhost', 11298))
def cl_recv():
while True:
try:
msg = client.recv(1024).decode('utf-8')
if msg == 'nick':
client.send(nick.encode('utf-8'))
else:
print(msg)
except:
print("Something went wrong! Bummer.")
client.close()
break
def cl_send():
while True:
msg = f'{nick}: {input("")}'
client.send(msg.encode('utf-8'))
receive_th = threading.Thread(target = cl_recv)
receive_th.start
Whenever I run the code (one cmd window for the server and two for the clients to test it out) it gives me this error:
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host
I'm guessing it's a problem with the client closing the server, but I'm using client.connect. I've looked at the code multiple times and can't figure out how to fix it.
This can be caused by the two sides of the connection disagreeing over whether the connection timed out or not during a keepalive. (Your code tries to reused the connection just as the server is closing it because it has been idle for too long.) You should basically just retry the operation over a new connection.

How to close Python socket server when all of its multiple clients close the connection?

I have made a multithreaded Python socket server.
It supports multiple socket client connections.
My code is:
import socket
from _thread import *
def multi_threaded_client(connection):
response = ''
while True:
data = connection.recv(10000000)
response += data.decode('utf-8')
if not data:
print(response)
break
connection.send(bytes(some_function_name(response), "utf-8"))
connection.close()
class socketserver:
def __init__(self, address='', port=9090):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.address = address
self.port = port
self.sock.bind((self.address, self.port))
self.cummdata = ''
def recvmsg(self):
self.sock.listen(65535)
self.conn, self.addr = self.sock.accept()
print('connected to', self.addr)
self.cummdata = ''
start_new_thread(multi_threaded_client, (self.conn, ))
return self.cummdata
def __del__(self):
self.sock.close()
serv = socketserver('127.0.0.1', 9090)
print('Socket Created at {}. Waiting for client..'.format(serv.sock.getsockname()))
while True:
msg = serv.recvmsg()
I also want the server to detect if any new client is connected to /disconnected from it.
Once all the clients are disconnected from it, I want the server to be closed on its own.
I could not figure this out

Persistent socket connection in Lua/Python

I'm trying to create a persistent socket connection between a Lua client and Python server. Effectively a script that'll constantly ping the server with keepalive messages
My current issue is that the socket closes after each connection without a means to reopen it for transmission.
Lua Client:
local HOST, PORT = "localhost", 9999
local socket = require('socket')
-- Create the client and initial connection
client, err = socket.connect(HOST, PORT)
client:setoption('keepalive', true)
-- Attempt to ping the server once a second
start = os.time()
while true do
now = os.time()
if os.difftime(now, start) >= 1 then
data = client:send("Hello World")
-- Receive data from the server and print out everything
s, status, partial = client:receive()
print(data, s, status, partial)
start = now
end
end
Python Server:
import socketserver
class MyTCPHandler(socketserver.BaseRequestHandler):
def handle(self):
self.data = self.request.recv(1024).strip()
print("{} wrote".format(self.client_address[0]))
print(self.data)
print(self.client_address)
# Send back some arbitrary data
self.request.sendall(b'1')
if __name__ == '__main__':
HOST, PORT = "localhost", 9999
# Create a socketserver and serve is forever
with socketserver.TCPServer((HOST, PORT), MyTCPHandler) as server:
server.serve_forever()
The expected result is a keepalive ping every second to ensure the client is still connected to the server.
I ended up finding a solution.
The problem seems to have been with the socketserver library in Python. I switched it to raw sockets and things began working how I wanted them to. From there I created threads to handle the back and forth in the background
Python Server:
import socket, threading
HOST, PORT = "localhost", 9999
# Ensures the connection is still active
def keepalive(conn, addr):
print("Client connected")
with conn:
conn.settimeout(3)
while True:
try:
data = conn.recv(1024)
if not data: break
message = data.split(b',')
if message[0] == b'ping':
conn.sendall(b'pong' + b'\n')
except Exception as e:
break
print("Client disconnected")
# Listens for connections to the server and starts a new keepalive thread
def listenForConnections():
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.bind((HOST, PORT))
while True:
sock.listen()
conn, addr = sock.accept()
t = threading.Thread(target=keepalive, args=(conn, addr))
t.start()
if __name__ == '__main__':
# Starts up the socket server
SERVER = threading.Thread(target=listenForConnections)
SERVER.start()
# Run whatever code after this
The Lua client didn't change in this scenario

Send TCP message at random time to one of several clients in python

I am trying to send a TCP message at random time, depending on when the user input is received, to one of several clients from which I am receiving data on a thread for each client.
I am storing the IP of each client inside an SQL database and I decide to which IP i want to send data based on user input. How should I approach sending a message to a specific client ? I don't know how I can gain access over each socket connection and use it to send messages.
Any device, links of examples, or code snippets are greatly welcome.
This is the server code that I have so far :
import socket
import threading
from database import Database
d = Database()
def Read_RFID_tag():
while True:
receiveID = raw_input("tag input : ")
d.updateTable(receiveID, 1);
print(receiveID)
class ThreadedServer(object):
def __init__(self, host, port):
self.host = host
self.port = port
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.bind((self.host, self.port))
def listen(self):
self.sock.listen(5)
while True:
client, address = self.sock.accept()
print("new client")
client.settimeout(60)
threading.Thread(target = self.listenToClient,args = (client,address)).start()
def listenToClient(self, client, address):
size = 1024
while True:
query_result = d.existsWashedInTable(address)
try:
data = client.recv(size)
if data:
# Set the response to echo back the received data
print(data)
response = data
d.addEntryToTable(response,address, 0)
client.send(response)
else:
raise error('Client disconnected')
except:
client.close()
return False
if __name__ == "__main__":
port_num = 5005
d.createTable()
threading.Thread(target=Read_RFID_tag).start()
ThreadedServer('',port_num).listen()

Categories

Resources