I have 3 servers I would like to link so that they communicate between each other. The goal is to run MapReduce in a distributed way.
I have a problem when proceeding to a multi-server connection using TCP socket in python.
I simplified the code so that it enhances the understanding of this particular problem.
IMPORTANT INFO : This exact code is sent and ran on every server of the list "computers" using the bash code given at the very bottom of this thread.
`
from _thread import *
import socket
from time import sleep
computers = ["137.194.142.130", "137.194.142.131", "137.194.142.133"]
list_PORT = [3652,4457, 6735, 9725]
idt = socket.gethostbyname(socket.gethostname())
SIZE = 1024
FORMAT = "utf-8"
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((idt, list_PORT[computers.index(idt)+1]))
server.listen()
sleep(4) #So that every server have time to listen before
# the other ones start to connect with the next part of the code
list_socket_rec = []
if computers.index(idt) != 0:
for server in computers[:computers.index(idt)]:
socket_nb = 0
skt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
list_socket_rec.append(skt)
list_socket_rec[socket_nb].connect((server, list_PORT[computers.index(idt)])) # error connection refused
socket_nb += 1
#In this loop, I'm trying to connect to every server whose index are "smaller" in the computers list (in order to not have duplicates)
The error that I get is the following: (occuring on the connect() function at the end of the code)
`
Traceback (most recent call last):
File "file", line 24, in <module>
list_socket_rec[socket_nb].connect((server, list_PORT[computers.index(idt)])) # fonctionne pas ==> connection refused
ConnectionRefusedError: [Errno 111] Connection refused
Does someone know how to solve this error please?
Shell code to run the servers :
`
#!/bin/bash
# A simple variable example
login="login"
remoteFolder="/tmp/$login/"
fileName="server"
fileExtension=".py"
computers=("137.194.142.130", "137.194.142.131", "137.194.142.133")
for c in ${computers[#]}; do
command0=("ssh" "$login#$c" "lsof -ti | xargs kill -9")
command1=("ssh" "$login#$c" "rm -rf $remoteFolder;mkdir $remoteFolder")
command2=("scp" "$fileName$fileExtension" "$login#$c:$remoteFolder$fileName$fileExtension")
command3=("ssh" "$login#$c" "cd $remoteFolder; python3 $fileName$fileExtension")
echo ${command0[*]}
"${command0[#]}"
echo ${command1[*]}
"${command1[#]}"
echo ${command2[*]}
"${command2[#]}"
echo ${command3[*]}
"${command3[#]}" &
done
`
I've tried to bind/connect on different port for each connection because I thought the problem could come from multipole connection on the same port but the error was still there.
I have tried to go manually on 2 of the servers, I ran the previous code on the first of the computers list and then on the second of the computers list, and the connection worked.
Related
I'm on a 2020.4 Kali Linux VM on VMWare Workstation 16 Player and I'm working with the Black Hat Python book by Justin Seitz. Right in the beginning of Chapter 2 he introduces a basic UDP client but for some reason, I get thrown a ConnectionResetError every time because either the port I'm sending to or the port I'm receiving from is occupied. I then added a line to make it bind to the address I'm sending to and it worked. Is it not automatically binding when I sendto()? If I'm pentesting, I shouldn't need the password/admin to bind when I make a UDP client.
Here is my code:
import socket
address = ('127.0.0.1', 80)
# Create a socket object.
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# I commented this out just for testing reasons.
# client.bind(address)
# Send some data.
client.sendto(b'AAABBBCCC', address)
# Receive some data.
data, addr = client.recvfrom(4096)
print(data)
Here's the error:
Traceback (most recent call last):
File ".\udp_client.py", line 15, in <module>
data, addr = client.recvfrom(4096)
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host
I apologize in advance if this is some dumb mistake on my part.
EDIT:
I changed the code to use a different port (65536) yet now it just doesn't print anything or end the script, it just keeps running.
I'd suggest you try using a port other than port 80 (default for all HTTP traffic) which is likely being used constantly and isn't a good port to try and hold onto, try port numbers > 1023
I'm a beginner in python socket programming and I have to send a message from the server to the client side . I have 2 python IDLES one for the server and one for the client. I have made the server file with no errors but when I create a connection socket in my client file and try to connect to server I get the error:
clientSocket.connect((servername,port))
ConnectionRefusedError: [WinError 10061] no connection could be made because the target machine actively refused it
I don't know how to deal with this error and I would appreciate your help with guiding me.
Thank you in advance.
My code:
Server:
from socket import *
port = 1234
serverSocket = socket(AF_INET,SOCK_STREAM)
serverSocket.bind(('',port))
serverSocket.listen()
print("Server has started")
data = "Network labs"
while True:
connectionSocket , addr = serverSocket.accept()
connectionSocket.send(data)
connectionSocket.close()
Client:
from socket import *
port = 1234
servername = 'localhost'
clientSocket = socket(AF_INET,SOCK_STREAM)
clientSocket.connect((servername,port)) #this is where the error happens
I would gradually try to understand where the problem is coming from.
Try to identify where the problem is:
Write an example which is available online and will surely works, and then you will know that the problem is in your code.
Try to use the same code on different computer, or a VM. If it will work there you will know that the problem is with the environment.
Try to find people with similar problems, you will usually won't be the first. - Errno 10061 : No connection could be made because the target machine actively refused it ( client - server ) - this seems nice.
Find out if your server is running correctly, checks if someone is listening on port 1234 before running the client. (Use netstat)
Few things which unrelated to the subject but will improve your coding:
1. Don't import *, it's just an easy way to get name collision.
2. Use conventions, it's just make everything nicer to read. https://www.python.org/dev/peps/pep-0008/
Of course you can ignore all of this, it's just an advice.
I have 2 computers on the same LAN. The first PC has an ip address 192.168.178.30, the other PC has an ip address 192.168.178.26.
Ping, traceroute, telnet, ssh, everything works between the two PCs. Both PCs run the same OS - CentOS 7 and both PCs have the same python version 2.7.5 (checked with the python -V command).
I copied simple python code from a computer networking book.
client.py
from socket import *
serverName = '192.168.178.30'
serverPort = 12000
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((serverName,serverPort))
sentence = raw_input('Input lowercase sentence: ')
clientSocket.send(sentence)
modifiedSentence = clientSocket.recv(1024)
print 'From Server:', modifiedSentence
clientSocket.close()
server.py
from socket import *
serverPort = 12000
serverSocket = socket(AF_INET,SOCK_STREAM)
serverSocket.bind(('192.168.178.30',serverPort))
serverSocket.listen(5)
print 'The server is ready to receive'
while 1:
connectionSocket, addr = serverSocket.accept()
sentence = connectionSocket.recv(1024)
capitalizedSentence = sentence.upper()
connectionSocket.send(capitalizedSentence)
connectionSocket.close()
The code works when it is ran on the same PC (where the server is listening on localhost).
When I run the client code on one PC and the server code on the other PC I get this error on the client side.
Traceback (most recent call last):
File "client.py", line 5, in <module>
clientSocket.connect((serverName,serverPort))
File "/usr/lib64/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 113] No route to host
Can someone help?
Check the firewall (on the server).
I stopped the firewall like Messa suggested and now it works.
service firewalld stop
I still don't understand what the problem was. I even tried using different distributions. Do all distributions have strict firewalls or something. For example Ubuntu to Ubuntu, Ubuntu to CentOS, CentOS to Ubuntu I still had the same problem (error).
~]#supervisord
Error: No config file found at default paths (/usr/etc/supervisord.conf, /usr/supervisord.conf, supervisord.conf, etc/supervisord.conf, /etc/supervisord.conf); use the -c option to specify a config file at a different path
For help, use /usr/bin/supervisord -h
You should use
ln -s /etc/supervisor/supervisord.conf /usr/etc/supervisord.conf
None of this stuff worked for me. I just connected both the devices to the same WiFi network and my program worked!
You can also get this same error ([Errno 113] No route to host) if you are trying to connect 2 devices on the same network. the error can be fixed by double checking to make sure both devices are connected to the mqtt_client or whatever you are using. as soon as I connected the device I was trying to talk to everything worked as to be expected.I would also check to make sure the right IP_Address is being passed
We had this problem. I am putting our findings here in case anyone else stumbles across this question like I did.
Our configuration:
Host A: IP address 192.168.0.1, netmask 255.255.255.0
Host B: IP address 192.168.1.1, netmask 255.255.254.0
Neither host has a default gateway.
We are connecting from Host B to Host A. (That is not a typo.) The connect call succeeds, but when we try to send data, we get errno 113 aka. EHOSTUNREACH aka. "No route to host".
The fix, of course, was to change the subnet on Host A to match Host B.
We were surprised to see this error on a connection within the same subnet / same LAN. And we were surprised that connect succeeded followed by send failing. And we were surprised to see this error on Host B even though the network configuration on Host B itself was fine.
Somehow, the incorrect subnet on Host A caused this error on Host B...
...and just like that, today I learned about ICMP "destination unreachable" messages.
I'm working on a script that grabs the banner from common ports of a host. I'm using sockets to make the connection but I'm facing some issues. Here is the code:
try:
connsocket = socket(AF_INET, SOCK_STREAM)
connsocket.settimeout( 5 )
connsocket.connect((ip, port))
connsocket.send("HEAD / HTTP/1.0")
results = connsocket.recv(400)
connsocket.close()
return str(results)
except:
print '[ERROR]Failed to connect or Connection timed out'
The are two major issues:
First time I run the script to a host all the banners are retrieved correctly except port 80 which exits with the timeout
The second problem is that when I relaunch the script to the same host there is no response from any port.
I suspect that the second issue is due to the connection is still open and the script fails retying to connect. With the first issue I have no idea why it's not working.
Any idea?
Regards.
Below is the code I am running within a service. For the most part the script runs fine for days/weeks until the script hiccups and crashes. I am not so worried about the crashing part as I can resolve the cause from the error logs an patch appropriately. The issue I am facing is that sometimes when the service restarts and tries to connect to the server again, it gets a (10061, 'Connection refused') error, so that the service is unable to start up again. The bizarre part is that there is no python processes running when connections are being refused. IE no process with image name "pythonw.exe" or "pythonservice.exe." It should be noted that I am unable to connect to the server with any other machine as well until I reset computer which runs the client script. The client machine is running python 2.7 on a windows server 2003 OS. It should also be noted that the server is coded on a piece of hardware of which I do not have access to the code.
try:
EthernetConfig = ConfigParser()
EthernetConfig.read('Ethernet.conf')
HOST = EthernetConfig.get("TCP_SERVER", "HOST").strip()
PORT = EthernetConfig.getint("TCP_SERVER", "PORT")
lp = LineParser()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
reader = s.makefile("rb")
while(self.run == True):
line = reader.readline()
if line:
line = line.strip()
lp.parse(line)
except:
servicemanager.LogErrorMsg(traceback.format_exc()) # if error print it to event log
s.shutdown(2)
s.close()
os._exit(-1)
Connection refused is an error meaning that the program on the other side of the connection is not accepting your connection attempt. Most probably it hasn't noticed you crashing, and hasn't closed its connection.
What you can do is simply sleep a little while (30-60 seconds) and try again, and do this in a loop and hope the other end notices that the connection in broken so it can accept new connections again.
Turns out that Network Admin had the port closed that I was trying to connect to. It is open for one IP which belongs to the server. Problem is that the server has two network cards with two separate IP's. Issue is now resolved.