python errno 23 - socket livestatus - python

I'm trying to send two queries to the server with this script, to get the MK Livestatus:
live.py
#!/usr/bin/python
socket_path = "/tmp/run/live"
import socket
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.connect(socket_path)
# Get Hosts
hosts = s.send("GET hosts\nColumns: name\n")
s.shutdown(socket.SHUT_WR)
hosts = s.recv(1024)
hosts = [ line.split(';') for line in hosts.split('\n')[:-1] ]
hostsB = s.send("GET hosts\nColumns: name\n")
s.close()
But I get this error:
Traceback (most recent call last): File "live.py", line 13, in
hostsB = s.send("GET hosts\nColumns: name\n") socket.error:
[Errno 32] Broken pipe
I think the error is related to the command "s.shutdown(socket.SHUT_WR)". But the author says, that this is required. You will get no answer (timeout?), if you remove this line.
How can I send two queries?
SOLUTION
so ... I've written a function that does the job :-)
Function
def sendQuery(query):
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.connect(socket_path)
s.send(query)
s.shutdown(socket.SHUT_WR)
answer = ''
while True:
data = s.recv(1024)
answer += data
if len(data) < 1024:
break
s.close()
return answer
Usage
sendQuery("GET hosts\nColumns: name\n")

so ... I've written a function that does the job :-)
Function
def sendQuery(query):
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.connect(socket_path)
s.send(query)
s.shutdown(socket.SHUT_WR)
answer = ''
while True:
data = s.recv(1024)
answer += data
if len(data) < 1024:
break
s.close()
return answer
Usage
sendQuery("GET hosts\nColumns: name\n")

Related

How do I troubleshoot this error: OSError: [Errno 9] Bad file descriptor

I am trying to figure out where the problem is coming from between my client and server files. The client receives the correct calculation done by the TCP server. However, the TCP server continues to throw an error after performing the task.
add_server.py
# This is add_server.py script
import socket
host = socket.gethostname()
port = 8096
s = socket.socket()
s.bind((host, port))
s.listen(5)
print('Waiting for connection...')
conn, addr = s.accept()
while True:
data = conn.recv(1024) # Receive data in bytes
print(data)
decoded_data = data.decode('utf-8') # Decode data from bystes to string
print(data)
d = decoded_data.split(",") # Split the received string using ',' as separator and store in list 'd'
add_data = int(d[0]) + int(d[1]) # add the content after converting to 'int'
conn.sendall(str(add_data).encode('utf-8')) # Stringify results and convert to bytes for transmission (String conversion is a must)
conn.close() # Close connection
add_client.py
# This add_client.py script
import socket
host = socket.gethostname()
port = 8096
s = socket.socket()
s.connect((host, port))
a = input('Enter first number: ')
b = input('Enter second number: ')
c = a + ', ' + b # Generate string from numbers
print('Sending string {} to sever for processing...'.format(c))
s.sendall(c.encode('utf-8')) # Converst string to bytes for transmission
data = s.recv(1024).decode('utf-8') # Receive server response (addition results) and convert from bystes to string
print(data) # Convert 'string' data to 'int'
s.close() # close connection
Full traceback
Traceback (most recent call last):
File "/home/sharhan/AWS/AWS-PERSONAL-COURSES/linux-networking-and-troubleshooting/python-networking/add_server.py", line 17, in <module>
data = conn.recv(1024) # Receive data in bytes
OSError: [Errno 9] Bad file descriptor
You are closing the socket inside the while loop in this line
while True:
data = conn.recv(1024)
# Rest of the code
conn.close()
So the next time you try to receive the data with conn.recv it results in an error.
To fix this simply close the connection after you're done receiving all the data.
while True:
data = conn.recv(1024)
# Rest of the code
conn.close()

Python Socket is not receiving messages sent to it

I made a socket connection between a client and server. I set it up so it makes a request for data, but it doesn't receive the data. It throws Traceback (most recent call last): File "C:\...file path...\server.py", line 38, in <module> s1.connect((host1, port1)) ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it, but it sends a response. How can I set it up to receive the message? By the way, it makes a request to the server to read a file.
Server.py:
import json
import socket
import base64
while True:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
with conn:
print('Connected by', addr)
while True:
data = conn.recv(1024)
data = repr(data)
data = str(data)
data1 = []
for i in range(len(data)):
data1.append(data[i])
data1[0] = ""
data1[1] = ""
data1[len(data1)-1] = ""
data ="".join(data1).replace("'","\"").replace("~","=")
if (data != ""):
print(data)
data = json.loads(data)
typer = data["type"]
if (typer == 'putreq'):
#Writes to file, there are no bugs here.
else:
host1 = addr[0]
port1 = addr[1]
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s1:
s1.connect((host1, port1))
with open(data["name"], 'r') as userfile:
data1 = userfile.read()
s1.sendall(bytes(base64.b64encode(bytes(data1,'utf-8')),'utf-8'))
s1.close
s.close()
Client.py:
import socket
import sys
import base64
import json
import random
import time
typec = sys.argv[1]
filec = sys.argv[2]
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.sendall(bytes(str({"type":'namereq',"name":filec}), "UTF-8"))
data = s.recv(1024)
data = repr(data)
data = str(data)
data1 = []
for i in range(len(data)):
data1.append(data[i])
data1[0] = ""
data1[1] = ""
data1[len(data1)-1] = ""
data ="".join(data1).replace("~","=")
if(data != ''):
print(data)
I think it has to do with the hostname and port being different on the server and the user.
modify this:
else:
host1 = addr[0]
port1 = addr[1]
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s1:
s1.connect((host1, port1))
with open(data["name"], 'r') as userfile:
data1 = userfile.read()
s1.sendall(bytes(base64.b64encode(bytes(data1,'utf-8')),'utf-8'))
s1.close
into this:
else:
with open(data["name"], 'r') as userfile:
data1 = userfile.read()
conn.sendall(bytes(base64.b64encode(bytes(data1,'utf-8')),'utf-8'))
conn.close
you already have a socket connected to that host and port no need to create others (also because i can see that HOST is equal to host1)

socket.gaierror: Errno 11004 getaddrinfo failed

i am trying to create a proxy server script with python when i run it i have this arror messages please can i know what are the mistakes i've done and how to avoid them (i sow the script on a site)
how the script looks like !
import socket
from thread import *
import sys
host = ""
port = 91
def start():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(5)
print "[+] listening ..."
while True:
try:
connection, address = s.accept()
data = connection.recv(1024)
start_new_thread(conn_string, (data, connection))
except KeyboardInterrupt:
print "\n\nclosing !"
def conn_string(data, con):
webserver = ""
portserver = 0
f_li = data.split('\n')[0]
lien = f_li.split(' ')[1]
http_pos = lien.find("://")
if http_pos == -1:
url = lien
else:
url = lien[(http_pos+3):]
port_pos = url.find(':')
if port_pos == -1:
portserver = 80
else:
portserver = url[(port_pos+1):]
s_pos = url.find('/')
if s_pos == -1:
webserver = url
else:
webserver = url[:(s_pos)]
proxy_server(webserver, portserver, data, con)
def proxy_server(webserver, portserver, data, con):
print webserver
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((webserver, int(portserver)))
s.send(data)
while True:
red = s.recv(8192)
if len(red) > 0:
con.send(red)
start()
this is one of the error messages that i have !
Unhandled exception in thread started by <function conn_string at 0x0248CEF0>
Traceback (most recent call last):
File "C:\Users\none2\Desktop\Nouveau dossier\Target.py", line 52, in conn_stri
ng
proxy_server(webserver, portserver, data, con)
File "C:\Users\none2\Desktop\Nouveau dossier\Target.py", line 57, in proxy_ser
ver
s.connect((webserver, int(portserver)))
File "C:\Python27\lib\socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
socket.gaierror: [Errno 11004] getaddrinfo failed
can you replace
start_new_thread(conn_string, (data, connection))
line with
start_new_thread(conn_string(data, connection))
tried running the same file, it seems above one is the only error

python3 OSError: [Errno 107] Transport endpoint is not connected

I try to make a chat on Python3. Here is my code:
import socket
import threading
print("Server starts working")
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(("", 57054))
sock.listen(2)
conn, addr = sock.accept()
def get_message():
while True:
data = sock.recv(1024).decode()
if len(data) != 0:
print("Some guy: ", data)
def send_message():
while True:
message = input()
if len(message) != 0:
message = str.encode(message)
sock.send(message)
print("You: ", message)
def run():
get_message_thread = threading.Thread(target=get_message())
send_message_thread = threading.Thread(target=send_message())
get_message_thread.daemon = True
send_message_thread.daemon = True
get_message_thread.start()
send_message_thread.start()
run()
sock.close()
But after the execution and sending a message from other client I get an error message:
Server starts working
Traceback (most recent call last):
File "/home/ptrknvk/Documents/Study/Python/chat/chat.py", line 40, in <module>
run()
File "/home/ptrknvk/Documents/Study/Python/chat/chat.py", line 30, in run
get_message_thread = threading.Thread(target=get_message())
File "/home/ptrknvk/Documents/Study/Python/chat/chat.py", line 15, in get_message
data = sock.recv(1024).decode()
OSError: [Errno 107] Transport endpoint is not connected
Process finished with exit code 1
I've read, that there are some troubles with sock.accept(), but everything's alright here, as I think.
Your program has many flaws. As zondo mentioned, you are incorrectly passing the target. They should be like threading.Thread(target=get_message). Second problem is, you should use conn (and not sock) for sending and receiving data. Third problem is, main thread was blocking at accept call and will wait for the connection. But soon as it accepts a connection, it will exit. From the main thread, you should wait for get_message_thread and send_message_thread. Try the modified code:
import socket
import threading
print("Server starts working")
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(("", 57054))
sock.listen(2)
conn, addr = sock.accept()
def get_message():
while True:
data = conn.recv(1024).decode()
if len(data) != 0:
print("Some guy: ", data)
def send_message():
while True:
message = input()
if len(message) != 0:
message = str.encode(message)
conn.send(message)
print("You: ", message)
def run():
get_message_thread = threading.Thread(target=get_message)
send_message_thread = threading.Thread(target=send_message)
get_message_thread.daemon = True
send_message_thread.daemon = True
get_message_thread.start()
send_message_thread.start()
get_message_thread.join()
send_message_thread.join()
run()
sock.close()

Connection reset by peer [errno 104] in Python 2.7

I've seen and read a lot about this particular issue on the internet.
I am writing a simple chat server and client using socket in python for learning purpose mainly.
I've observed an issue here.
Here is my server code :
__author__ = 'pchakraverti'
import socket
import select
import sys
class NickSocketMap(object):
count = 0
def __init__(self, nick, client_socket):
self.nick = nick
self.client_socket = client_socket
NickSocketMap.count += 1
#staticmethod
def display_count():
print "Total number of clients is %d" % NickSocketMap.count
host = ""
port = 7575
socket_list = []
nick_list = []
cnt = 0
recv_buffer = 1024
def register_nick(nick, client_socket):
obj = NickSocketMap(nick, client_socket)
nick_list.append(obj)
def process_request(request_string, client_socket):
parts = request_string.split("|")
if parts[0] == "set_nick":
register_nick(parts[1], client_socket)
client_socket.send("nick_set")
elif parts[0] == "transmit_msg":
broadcast_message(parts[1], parts[2])
return 1
def broadcast_message(message, client_nick):
for s in nick_list:
if s.nick == client_nick:
try:
s.client_socket.send(message)
except socket.errno, ex:
print ex
break
def run_server():
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.bind((host, port))
except socket.errno, ex:
print ex
sys.exit(-1)
sock.listen(10)
# add the parent socket in the list
socket_list.append(sock)
# keep the server alive
while True:
try:
read_ready, write_ready, in_error = select.select(socket_list, [], [], 0)
except select.error, ex:
print ex
continue
for s in read_ready:
# check if s is the parent socket
if s == sock:
# accept new connection and append to list
try:
con, addr = s.accept()
if con not in socket_list:
socket_list.append(con)
except socket.errno, ex:
print ex
else:
try:
# receive packet from connected client
packet = s.recv(recv_buffer)
if not packet:
socket_list.remove(s)
read_ready.remove(s)
for n in nick_list:
if n.client_socket == s:
nick_list.remove(n)
break
break
print packet
except socket.errno, ex:
print ex
continue
process_request(packet, s)
sock.close()
if __name__ == "__main__":
run_server()
and here is my client code:
__author__ = 'pchakraverti'
import socket
nick = ""
host = "192.168.0.167"
port = 7575
sock = ""
def welcome():
print "Welecome to SecuChat!"
print "---------------------"
def init():
nick = raw_input("Enter your chat nickname : ")
print nick
global sock
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.connect((host, port))
except socket.errno, ex:
print ex
sock.send("set_nick|"+nick)
#sock.close()
if __name__ == "__main__":
welcome()
init()
In the client code, when I don't do the sock.close(), the server runs into an exception :
Traceback (most recent call last):
File "server.py", line 102, in <module>
run_server()
File "server.py", line 84, in run_server
packet = s.recv(recv_buffer)
socket.error: [Errno 104] Connection reset by peer
how ever, when I add that line, the problem doesn't occur.
Now I've two questions :
i) I've handled exceptions in the server.py, why is this exception not being handled and why is it crashing the code ? How can I make the server more robust and what am I missing ?
ii) What is the logic behind this crash and exception in relation to the sock.close() line in the client ?
i) Your try-except block doesn't catch any exceptions.
The first argument to except must be the type of the exception you want to catch. socket.errno is not an exception class but a module. You need to catch socket.error:
except socket.error, ex:
print ex
It "crashes" your code because any exception that isn't handled somewhere in the call stack propagates outwards until it hits an except. If there is no handler the program is terminated.
ii) When the client terminates without closing the connection, a RST packet is sent by the TCP/IP stack of your OS. This is roughly the equivalent of hanging up a phone without saying goodbye. Python converts this into an exception with the text "Connection reset by peer". It simply means that since you called read() Python assumed you expect to receive something and when the connection suddenly disconnected, Python informs you of this by raising the exception.

Categories

Resources