So I'm trying to create a python script that will allow multiple TCP connections from different computers and allow talking over the serial from the TCP client. Here is what I was playing with
import sys
import os
import time
import fileinput
import socket
import serial
import thread
serialData = serial.Serial('/dev/ttyS0',9600)
import argparse
def on_new_client(clientsocket,addr):
while True:
msg = clientsocket.recv(1024)
#do some checks and if msg == someWeirdSignal: break:
print addr, ' >> ', msg
serialData.write(msg)
#msg = raw_input('SERVER >> ')
#Maybe some code to compute the last digit of PI, play game or
anything else can go here and when you are done.
clientsocket.send(msg)
clientsocket.close()
def on_Send_client(clientsocket,addr):
while True:
x = serialData.readline()
clientsocket.send(x)
clientsocket.close()
s = socket.socket()
host = '' #ip of raspberry pi
port = 12345
s.bind((host, port))
s.listen(5)
serialData.isOpen()
serialData.write("This is a test")
while True:
c, addr = s.accept()
thread.start_new_thread(on_new_client,(c,addr))
#thread.start_new_thread(on_Send_client,(c,addr))
s.close()
Right now I can connect with multiple TCP clients and eco their data. Their data also gets sent out the serial port. How should I go about buffering the serial data and sending it back out any and all connections that are active? Seems like nothing I look for online can do this correctly and Socat command even fails for multiple connections to serial.
Related
I know that I can see inside of network traffic for example with WireShark. When i use GET on HTML I can see those stuff in URL, what should not be problem what I am doing. But I believe GET,POST and maybe REQUEST too, as I did not work with that one yet can bee seen on something like Wire Shark network analyzer.
I am making Python client, what i will put on computers in network to show their IP,Host Name and Users on PC. This client will be as gate to the computer for remote control. As our management does not want to spend money for windows server, or other management system we need to get something free to manage all computers.
I am also seeking advice how I could do it as you are more skilled then me here.
I found few ways.
With the client create SSH Gateway for receiving commands.
With Client enable the Powershell remote option, then just push scripts to all computers at once.
Use some way the API requests etc... I am not skilled in this one at all, but I believe this is the way how other similar programs works?
As this client would create big security risk, I am first seeking way what is best way to hide it from network. Probably I will need to come up with some Private and public Key system here as well.
What are yours suggestions please on this topic?
here is just very short code I am playing with to receive basic info as IP, Host name and all Users
the Flask website showing those values is just for test, It will not be there once it is deployed
Update
I took advice from MarulForFlask but I got a couple issues. First this i think can have only one connection at a time. And second if possible Can i get the output of console from the client PC on screen of Server PC?
I want this output only for testing, as I know if i do something like netstat or any other command with multiple clients it would filled up screen with too many text... Currently I am getting back text format as plaintext with \r \n ... and other text deviders.
I am now trying Multicast, but i am getting error for binding the multicast IP.
OSError: [WinError 10049] The requested address is not valid in its context
Master.py
import time
import socket
import sys
import os
valueExit = True
# Initialize s to socket
s = socket.socket()
# Initialize the host
host = socket.gethostname()
BUFFER_SIZE = 1024
# Initialize the port
port = 8080
# Bind the socket with port and host
s.bind(('', port))
print("waiting for connections...")
# listening for conections
s.listen()
# accepting the incoming connections
conn, addr = s.accept()
print(addr, "is connected to server")
def send_query():
keepAllive, repeatIt = True, False
print("""To exit session write: EndSession
For help write: help
""")
while (keepAllive == True):
# commands for server use only
innerCommands = ["endsession", "help"]
# take command as input
command = input(str("Enter Command : "))
if command not in innerCommands:
conn.send(command.encode())
print("Command has been sent successfully.")
keepAllive = False
repeatIt = True
elif (command == "endsession"):
conn.send(command.encode())
valueExit = False
elif (command == "help"):
print("""To exit session write: EndSession""")
while (repeatIt == True):
# recieve the confrmation
data = conn.recv(BUFFER_SIZE)
if data:
print(f"command recieved and executed sucessfully.\n {data}")
keepAllive = True
repeatIt = False
else:
print("No reply from computer")
keepAllive = True
repeatIt = False
while valueExit == True:
send_query()
Slave.py
import time
import socket
import sys
import subprocess
import os
stayOn = True
def establishConnection():
# Initialize s to socket
s = socket.socket()
# Initialize the host
host = "127.0.0.1"
# Initiaze the port
port = 8080
keepAlive = True
try:
# bind the socket with port and host
s.connect((host, port))
print("Connected to Server.")
while keepAlive == True:
# recieve the command from master program
command = s.recv(1024)
command = command.decode()
# match the command and execute it on slave system
if command == "endsession":
print("Program Ended")
keepAlive = False
elif command != "":
# print("Command is :", command)
#s.send("Command recieved".encode())
proc = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)
(out, err) = proc.communicate()
s.send(f"{out}".encode())
print("program output:", out)
except Exception as err:
print(f"Error: {err}")
s.send(f"Error: {err}".encode())
while stayOn == True:
establishConnection()
see:
https://www.pythonforthelab.com/blog/how-to-control-a-device-through-the-network/
There uses a flask webserver.
otherwise, create a master.py file and paste this code:
import time
import socket
import sys
import os
# Initialize s to socket
s = socket.socket()
# Initialize the host
host = socket.gethostname()
# Initialize the port
port = 8080
# Bind the socket with port and host
s.bind(('', port))
print("waiting for connections...")
# listening for conections
s.listen()
# accepting the incoming connections
conn, addr = s.accept()
print(addr, "is connected to server")
# take command as input
command = input(str("Enter Command :"))
conn.send(command.encode())
print("Command has been sent successfully.")
# recieve the confrmation
data = conn.recv(1024)
if data:
print("command recieved and executed sucessfully.")
open a slave.py and paste this code:
import time
import socket
import sys
import os
# Initialize s to socket
s = socket.socket()
# Initialize the host
host = "127.0.0.1"
# Initiaze the port
port = 8080
# bind the socket with port and host
s.connect((host, port))
print("Connected to Server.")
# recieve the command from master program
command = s.recv(1024)
command = command.decode()
# match the command and execute it on slave system
if command == "open":
print("Command is :", command)
s.send("Command recieved".encode())
# you can give batch file as input here
os.system('ls')
open slave.py in client, master.py in server
https://www.geeksforgeeks.org/how-to-control-pc-from-anywhere-using-python/
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()
I'm trying to write socket programming in python. Whenever client sends message to server, LED should start blinking.
I'm running server program on Raspberry pi and client on PC.
Here is the code of server which is running on my Pi.
#!/usr/bin/python # This is server.py file
import socket # Import socket module
import time
import RPi.GPIO as GPIO # Import GPIO library
GPIO.setmode(GPIO.BOARD) # Use board pin numbering
GPIO.setup(11, GPIO.OUT) # Setup GPIO Pin 11 to OUT
GPIO.output(11,False) # Init Led off
def led_blink():
while 1:
print "got msg" # Debug msg
GPIO.output(11,True) # Turn on Led
time.sleep(1) # Wait for one second
GPIO.output(11,False) # Turn off Led
time.sleep(1) # Wait for one second
GPIO.cleanup()
s = socket.socket() # Create a socket object
host = "192.168.0.106" # Get local machine name
port = 12345 # Port
s.bind((host, port)) # Bind to the port
s.listen(5) # Now wait for client connection.
while True:
c, addr = s.accept() # Establish connection with client.
print 'Got connection from', addr
msg = c.recv(1024)
msg1 = 10
if msg == msg1:
led_blink()
print msg
c.close()
Here is the code of client which is running on my PC.
#!/usr/bin/python # This is client.py file
import socket # Import socket module
s = socket.socket() # Create a socket object
host = "192.168.0.106" # Get local machine name
port = 12345 # port
s.connect((host, port))
s.send('10')
s.close
I'm able to receive the message from client, But not able to blink the LED.
Sorry I'm new to coding. I've pretty good knowledge in hardware but not in software.
Please help me.
Try this on your PC or Raspberry and then edit accordingly:
#!/usr/bin/python # This is server.py file
import socket # Import socket module
def led_blink(msg):
print "got msg", msg # Debug msg
s = socket.socket() # Create a socket object
host = "127.0.0.1" # Get local machine name
port = 12345 # Port
s.bind((host, port)) # Bind to the port
s.listen(5) # Now wait for client connection.
print "Listening"
c, addr = s.accept() # Establish connection with client.
while True:
msg = c.recv(1024)
print 'Got connection from', addr
if msg == "Exit":
break
led_blink(msg)
c.close()
and:
#!/usr/bin/python # This is client.py file
import socket, time # Import socket module
s = socket.socket() # Create a socket object
host = "127.0.0.1" # Get local machine name
port = 12345 # port
s.connect((host, port))
x=0
for x in range(10):
s.send('Message_'+str(x))
print x
time.sleep(2)
s.send('Exit')
s.close
Note that I am using both the server and client on the same machine 127.0.0.1 and removed the GPIO bits as I don't have them available.
You are comparing a string "10" with a number 10. Change your server code to :
msg1 = "10"
I'm trying to write code for a chat server using sockets for multiple clients. But it is working for only a single client. Why is it not working for multiple clients?
I have to perform this program using Beaglebone Black. My server program will be running on beaglebone and normal clients on gcc or terminal. So I can't use multithreading.
#SERVER
import socket
import sys
s=socket.socket()
s.bind(("127.0.0.1",9998))
s.listen(10)
while True:
sc,address = s.accept()
print address
while True:
msg = sc.recv(1024)
if not msg:break
print "Client says:",msg
reply = raw_input("enter the msg::")
sc.send(reply)
sc.close()
s.close()
#CLIENT
import socket
import sys
s= socket.socket()
s.connect(("127.0.0.1",9998))
while (1):
msg = raw_input("enter the msg")
s.send(msg)
reply = s.recv(1024)
print "Server says::",reply
s.close()
Use an event loop.
Integrated in python like asyncio : Echo server example
or use an external library that provides the event loop like libuv: Echo server example.
Note: Your code is not working for multiple clients simultaneously beacause you are blocked in the receive operation and you are not handling new accept operations.
I am trying to write a simple webserver on an Arduino to test a few things, but I couldn't find my Arduino with Ethernet on it.
"No worries" I thought, "I'll just write a socket server in python that acts as a proxy for the serial connection".
import socket
import serial
host = ''
port = 8001
buffSize= 1024
serverSocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
serverSocket.bind((host, port))
serverSocket.listen(1)
ser = serial.Serial('COM3', 115200, timeout=None, dsrdtr =False,rtscts =False,xonxoff =False)
print "Listening..."
send = ""
while 1:
conn, remoteAddr = serverSocket.accept()
print "Connection...."
data = conn.recv(buffSize)
print "Recieved"
ser.write("%s\n"%data)
print "Sent"
print "Attempting to get reply"
while ser.inWaiting()>0:
conn.send( ser.read())
conn.close()
serverSocket.close()
However, whatever I try, it seems that the connection made by the browser resets randomly and I'd get multiple rows of data. And the script resets the Arduino each time it connects or disconnects from the serial port. I tried using RealTerm and I got a proper answer, but python and serialness is just a mess.
Can anyone help me?
Use the tcp_serial_redirect.py script in the PySerial documentation. Is all you need.