Connecting two server in socket - python

I am a newbie in socket programming but i have a trouble that i have two server started on my localhost on port 3500 and 5000.Now i want thatmy client fist connect to the port 3500 perform some operation and then disconnect from 3500 while server will be running only client wil disconnect from 3500 and the it will connect to port 5000 and agian perform some operations.
I am using the below code to do this but getting error:-
import socket
s=socket.socket()
s.connect(('127.0.0.1',3500))
print("connectd to 3500")
print("hello friends")
s.close()
print("disconnect from 3500")
s.connect(('127.0.0.1',5000))
print("connected to 5000")
s.close()
But it is not able to connect to the second connection i.e port 5000.It gets connected to port 3500 successfully but while connecting to 5000 it throws an error.
Please any one to short out my mistake
Error:-
File "C:\Users\Lal rishav\Desktop\HubPort\test.py", line 9, in <module>
s.connect(('127.0.0.1',5000))
File "C:\Python27\lib\socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
File "C:\Python27\lib\socket.py", line 174, in _dummy
raise error(EBADF, 'Bad file descriptor')

You cannot do any operations on a closed socket, create a new one instead.
s.close()
# the socket is closed, you can't use it anymore!
# get another one:
s2 = socket.socket()
s2.connect(('127.0.0.1',5000))
s2.close()
# now s2 is closed, you can't use it anymore!

Related

Receive data from a client/server doesn't work

I developed a small Python program which should receive and output data from another client or server. However, I get an error message which is unknown to me. Can anyone help me? Thanks a lot
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('192.168.1.34', 80))
from_server = client.recv(4096)
client.close()
print from_server
Error:
Traceback (most recent call last):
File "CallManager2.py", line 4, in <module>
client.connect(('192.168.1.34', 80))
File "/usr/lib/python2.7/socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 111] Connection refused
The error comes from inability for your program to reach the server or other client.
Check that there is something listening to incoming connexions on the address you want to connect to.
Then you can check that the address you want to connect to is on the same network as your program.

How to use python's sshtunnel to connect to a router running only telnet?

I have to connect to a jumpserver to connect to a bunch of routers running only telnet. I'm new to SSH tunneling, but I've figured out that on the command line on my local machine, the following command forms the necessary tunnel:
$ ssh -fNL 2300:remote_host:23 user#jumpServer
Then all I have to do is connect to port 2300 on the local machine for the traffic to be forwarded to port 23 on the router (which doesn't have SSH and only has telnet):
> telnet localhost 2300
I have a few questions:
Where does the actual tunnel form? As I said, the router has port 22 blocked, i.e., it isn't capable of running SSH. However, my local machine and the gateway/jumpserver can. So, if the tunnel's forming between my local machine and the jump server, what is the mode of transport between the jumpserver and the router?
If I understand this right, there's a listener on my local machine on port 2300, that forwards all traffic to some port on the jump server via the SSH tunnel, that then forwards it to the router. Right?
[Python Specific question] How do I get the sshtunnel module to do this programmatically? I tried the following:
from sshtunnel import open_tunnel
from telnetlib import Telnet
js = '123.456.555.666'
js_usr = "user"
rem_host = '123.456.789.101'
with open_tunnel(
ssh_address_or_host=(js, 22),
ssh_username=js_usr,
ssh_password="password",
remote_bind_address=(rem_host, 23)
) as tunnel:
with Telnet(js, tunnel.local_bind_port, 10) as tn:
tn.interact()
However, this throws the following error:
Traceback (most recent call last):
File "C:/Users/somsinha/PycharmProjects/SysTEst/sshTunnelTest.py", line 14, in
with Telnet(js, tunnel.local_bind_port, 10) as tn:
File "C:\Users\somsinha\bin\WPy64-3741\python-3.7.4.amd64\lib\telnetlib.py", line 218, in init
self.open(host, port, timeout)
File "C:\Users\somsinha\bin\WPy64-3741\python-3.7.4.amd64\lib\telnetlib.py", line 234, in open
self.sock = socket.create_connection((host, port), timeout)
File "C:\Users\somsinha\bin\WPy64-3741\python-3.7.4.amd64\lib\socket.py", line 727, in create_connection
raise err
File "C:\Users\somsinha\bin\WPy64-3741\python-3.7.4.amd64\lib\socket.py", line 716, in create_connection
sock.connect(sa)
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it
How to I make python ssh -fNL 2300:remote_host:23 user#jumpServer manually?
Everything is right with your code except use should use "localhost" with telnet:
from sshtunnel import open_tunnel
from telnetlib import Telnet
js = '123.456.555.666'
js_usr = "user"
rem_host = '123.456.789.101'
with open_tunnel(
ssh_address_or_host=(js, 22),
ssh_username=js_usr,
ssh_password="password",
remote_bind_address=(rem_host, 23)
) as tunnel:
# Use localhost as host
with Telnet('localhost', tunnel.local_bind_port, 10) as tn:
tn.interact()
The reason is the port is forwarded to the localhost and it must be accessed from it.

How to close socket after python fail?

First, I encountered sockets in Python and faced this problem: when some error in my python code occurs, for example some syntax error before conn.close() on the second script start port is in use. The script already finished, but the socket is still open, kind of like busy socket.
Here is an error just for example:
web#web-X501A1 /var/www $ cd /home/web/www/public/py
web#web-X501A1 ~/www/public/py $ python sockets.py
connected: ('127.0.0.1', 47168)
Traceback (most recent call last):
File "sockets.py", line 164, in <module>
data = re.find('(<onvif>.*<\/onvif>)')
AttributeError: 'module' object has no attribute 'find'
web#web-X501A1 ~/www/public/py $ python sockets.py
Traceback (most recent call last):
File "sockets.py", line 154, in <module>
sock.bind(('', 9090))
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 98] Address already in use
web#web-X501A1 ~/www/public/py $ python sockets.py
Traceback (most recent call last):
File "sockets.py", line 154, in <module>
sock.bind(('', 9090))
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 98] Address already in use
Code:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('', 9090))
sock.listen(1)
conn, addr = sock.accept()
try:
print 'connected:', addr
buffer = ''
while True:
buffer += conn.recv(1024)
data = re.find('(<code>.*<\/code>)', buffer)
print data
exit();
if not data:
continue
conn.send(data.upper())
except Exception:
pass
finally:
conn.close()
Enclose the usage of the socket in a try/finally clause. Close the socket in the finally part. Perhaps handle the exception in an except part. Something similar to this:
try:
result = x / y
except ZeroDivisionError:
print "division by zero!"
else:
print "result is", result
finally:
print "executing finally clause"
The problem here is the dirty socket closing which occurs when the script crashes without the proper TCP connection shutdown sequence. Thankfully there's a simple solution which tells the kernel to ignore the fact the socket is already in use (the port it's bound to):
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
That's all, add that before the bind call and you're set. Debugging your other errors will be much simpler and less time consuming once that's done ;) See more in the docs https://docs.python.org/2/library/socket.html#socket.socket.setsockopt
If you use netstat -nutap you should notice that you connection seems like it's still up, on a state named TIME_WAIT.
That's part of TCP protocol, and according to wikipedia:
represents waiting for enough time to pass to be sure the remote TCP
received the acknowledgment of its connection termination request.
[According to RFC 793 a connection can stay in TIME-WAIT for a maximum
of four minutes known as a MSL (maximum segment lifetime).]
So, when you try to reconnect immediately to the same port, python complains that this port is still busy and cant be bound yet, saying:
socket.error: [Errno 98] Address already in use
See this old question, where it is asked how to avoid this waiting time.

Why is this MQTT client example failing?

I am trying out MQTT for the first time using Python and the mosquitto library. My client program is below. I'm trying to use the public demo MQTT server at http://www.mqtt-dashboard.com/subscribe. However the client code is failing, see error below. Any ideas on what's going on?
#!/usr/bin/env python
import mosquitto
client = mosquitto.Mosquitto("fredtest", clean_session=True)
client.connect("broker.mqttdashboard.com", 1883)
client.publish("fred.test", "hello world", 1)
client.loop_forever()
Error message:
C:\tmp>python mqttclient.py
Traceback (most recent call last):
File "mqttclient.py", line 6, in
client.connect("broker.mqttdashboard.com", 1883)
File "build\bdist.win-amd64\egg\mosquitto.py", line 582, in connect
File "build\bdist.win-amd64\egg\mosquitto.py", line 657, in reconnect
File "c:\python27\lib\socket.py", line 571, in create_connection
raise err
socket.error: [Errno 10060] A connection attempt failed because the connected pa
rty did not properly respond after a period of time, or established connection f
ailed because connected host has failed to respond
I'm not currently able to connect any client to broker.mqttdashboard.com:1883 - so this probably isn't an issue with your code.
To sanity check, have you tried connected to another broker, such as iot.eclipse.org:1883 ?

Can not start smtp in Python

I tried to start a smtp server with python with the following code:
import smtplib
smtp_server = smtplib.SMTP('localhost')
And I get the following error:
File "test.py", line 2, in <module>
smtp_server = smtplib.SMTP('localhost')
File "/usr/local/lib/python2.7/smtplib.py", line 242, in __init__
(code, msg) = self.connect(host, port)
File "/usr/local/lib/python2.7/smtplib.py", line 302, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/usr/local/lib/python2.7/smtplib.py", line 277, in _get_socket
return socket.create_connection((port, host), timeout)
File "/usr/local/lib/python2.7/socket.py", line 571, in create_connection
raise err
I tried to telnet localhost 25 and telnet localhost but they both give the following error:
Trying 127.0.0.1...
telnet: connect to address 127.0.0.1: Connection refused
telnet: Unable to connect to remote host: Connection refused
The same python code runs perfectly well on one of my other machines.
Any advice ?
Thanks.
UPDATE:
The machine I'm having problem with is running Python 2.7.2, while the machine that the code works well is running Python 2.6.2. I don't know if this is one of the reasons.
smtplib is SMTP protocol client. What you are looking for is smtpd.
The problem is that smtplib does not provide an SMTP server implementation, it implements SMTP client. Most likely, the code tries to connect to localhost and fails. See http://docs.python.org/2/library/smtplib.html
Is the other machine you write about already running an SMTP server?
And what are you trying to do?

Categories