I communicate Python with Matlab via sockets. However, even before going there, I want to test sockets with netcat. So I establish server using nc -lkp 25771, and make Python client to send a message to this server:
import socket
host = 'localhost'
port = 25771
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host,port))
s.send('Hello there')
s.close()
After running python client.py server prints out 'Hello there'; however, after I try to run client script one more time it raises exception.
Traceback (most recent call last):
File "client.py", line 13, in
s.connect((host,port))
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 111] Connection refused
Why the same command raises the error second time? What changes after my first command?
You are using traditional version of netcat (netcat-traditional) which doesn't support -k option. you can confirm checking the man page of your netcat by typing man nc in your terminal .
Install the netcat-openbsd version using the command
sudo apt-get install netcat-openbsd
now switch to netcat-openbsd version using the command
sudo update-alternatives --config nc
and choose the netcat-openbsd .
now you can use nc -lk 25771 .
this listens on port 25771 for multiple connections .
you can also use the commands discussed here
Netcat: using nc -l port_number instead of nc -l -p port_number
Related
I am new to paho-mqtt. I was trying to publish a topic using my localhost and I encountered the following error :
Traceback (most recent call last):
File "server.py", line 10, in <module>
client1.connect(host,port,keepalive)
File "/usr/local/lib/python2.7/dist-packages/paho_mqtt-1.3.1-py2.7.egg/paho/mqtt/client.py", line 768, in connect
return self.reconnect()
File "/usr/local/lib/python2.7/dist-packages/paho_mqtt-1.3.1-py2.7.egg/paho/mqtt/client.py", line 895, in reconnect
sock = socket.create_connection((self._host, self._port), source_address=(self._bind_address, 0))
File "/usr/lib/python2.7/socket.py", line 575, in create_connection
raise err
socket.error: [Errno 111] Connection refused
My python code is below :
import paho.mqtt.client as paho
port=1883
host = "localhost"
keepalive = 60
def on_publish(client,userdata,result):
print("data published \n")
pass
client1= paho.Client("control1")
client1.on_publish = on_publish
client1.connect(host,port,keepalive)
ret= client1.publish("Robot","Robot 1 move_left")
When I run the same code with iot.eclipse.org as host then it works fine. Any help would be highly appreciated.
I was facing the same issue.
The solution was to install a local MQTT broker.
http://www.steves-internet-guide.com/install-mosquitto-linux/
The exposed docker port for mqtt is usually different than 1883.
I use the official eclipse mosquitto docker and the run example on their page is something like:
sudo docker run -it -p 11883:1883 -p 9001:9001 eclipse-mosquitto
therefore the client should connect to port 11883
client.connect(broker_address, 11883)
I wrote a generic script on Python that supports Windows and Unix ssh connection from Unix.
When I try Unix command from Unix to create dir in Windows, I get exit 53
/usr/bin/ssh2 --password pass -l admin ip_address mkdir "C:\Temp\ALEX_TEST_EX" &
When I write only /usr/bin/ssh2 --password pass -l admin ip_address, it is Ok. I login to Windows
When I try C:\Temp\ALEX_TEST_EX on this machine manually it is also Ok.
What is problem?
I also try to use with Python ssh2 command like
import paramiko
ssh = paramiko.SSHClient()
ssh.connect("ip_address", username="admin", password="pass")
but I get exceptions
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/python3.5/site-packages/paramiko/client.py", line 402, in connect
self, server_hostkey_name, server_key
File "/python3.5/site-packages/paramiko/client.py", line 768, in missing_host_key
'Server {!r} not found in known_hosts'.format(hostname)
paramiko.ssh_exception.SSHException: Server 'X.Y.Z.W' not found in known_hosts
You have not configued the client machine to allow you to know the server you are trying to connect to. You can either configure the client, or as a work around you can set the MissingHostKeyPolicy on paramiko like:
Code:
To warn when host not in known hosts:
ssh.set_missing_host_key_policy(paramiko.WarningPolicy)
To auto add host to know hosts:
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy)
Full Code:
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.WarningPolicy)
ssh.connect("localhost", username="admin", password="pass")
I'm working on a simple setup for a Raspberry PI to communicate with a server via RabbitMQ and I'm not making a connection. Here is the setup:
Client: Raspberry PI (Raspbien Debian 8.0) with Python 2.7 and Pika 0.10.0
RabbitMQ Server: MacMini running 10.11.6 - OS X El Capitan with Docker
Docker execution on Mac:
docker run -v /Users/tigelane/Documents/Development/brimstone_manager:/var/lib/rabbitmq -d --hostname my-rabbit --name some-rabbit rabbitmq:3
Python code to execute on client:
def rabbit_post():
entry = get_ipaddress()
post_time = datetime.datetime.now().strftime("%d %B %Y : %I:%M%p")
rabbit_server = 'machine.tigelane.com'
credentials = pika.PlainCredentials('machine', 'machine')
connectionParams = pika.ConnectionParameters(host=rabbit_server, credentials=credentials)
connection = pika.BlockingConnection(connectionParams)
channel = connection.channel()
channel.queue_declare(queue='hello')
try:
channel.basic_publish(exchange='', routing_key='hello', body='Hello World!')
print(" [x] Sent 'Hello World!'")
except:
print ("Unable to post to server: {}".format(rabbit_server))
connection.close()
I kept seeing this error:
Traceback (most recent call last): File "./brimstone_post.py", line
75, in
main() File "./brimstone_post.py", line 71, in main
rabbit_post() File "./brimstone_post.py", line 58, in rabbit_post
connection = pika.BlockingConnection(connectionParams) File "/usr/local/lib/python2.7/dist-packages/pika/adapters/blocking_connection.py",
line 339, in init
self._process_io_for_connection_setup() File "/usr/local/lib/python2.7/dist-packages/pika/adapters/blocking_connection.py",
line 374, in _process_io_for_connection_setup
self._open_error_result.is_ready) File "/usr/local/lib/python2.7/dist-packages/pika/adapters/blocking_connection.py",
line 395, in _flush_output
raise exceptions.ConnectionClosed() pika.exceptions.ConnectionClosed
I had read a few other posts and tried some things like the following to troubleshoot:
Viewing the rabbitmq logs: docker logs some-rabbit The log file
didn't show any connection.
Capturing traffic on the raspberry to
see if I'm even trying to send traffic to the server: sudo tcpdump
port 5672
Making sure the Firewall was turned off / ports open on the Mac.
I finally realized that on the Docker container there is not -p option to forward ports to the container. I changed the container to open ports 5672 on the command-line and and now it's working. Hope this can help someone else that might be using the documents from hub.docker.com on RabbitMQ.
This is the example they give for the docker container: $ docker run -d --hostname my-rabbit --name some-rabbit rabbitmq:3
This is the new command I'm using to start my RabbitMQ docker container and it's working well: docker run -v /Users/tigelane/Documents/Development/brimstone_manager:/var/lib/rabbitmq -d --hostname my-rabbit --name some-rabbit -p 5672:5672 rabbitmq:3
While I think I have solved my problem, I have this nagging feeling that I'm missing something (besides other ports that I might need to add) and that there may have been a reason that the port was omitted on the example, or maybe they just left it off thinking everyone would add the port naturally because that's how you use Docker containers. Either way, please feel free to correct my mistake.
So basically I have this remote computer with a bunch of files.
I want to run unix commands (such as ls or cat) and receive them locally.
Currently I have connected via python's sockets (I know the IP address of remote computer). But doing:
data = None
message = "ls\n"
sock.send(message)
while not data:
data = sock.recv(1024) <- stalls here forever
...
is not getting me anything.
There is an excellent Python library for this. It's called Paramiko: http://www.paramiko.org/
Paramiko is, among other things, an SSH client which lets you invoke programs on remote machines running sshd (which includes lots of standard servers).
You can use Python's subprocess module to accomplish your task. It is a built-in module and does not have much dependencies.
For your problem, I would suggest the Popen method, which runs command on remote computer and returns the result to your machine.
out = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE, stderr=subprocess.PIPE)
t = out.stdout.read() + out.stderr.read()
socket.send(t)
where cmd is your command which you want to execute.
This will return the result of the command to your screen.
Hope that helps !!!
This is what I did for your situation.
In terminal 1, I set up a remote shell over a socket using ncat, a nc variant:
$ ncat -l -v 50007 -e /bin/bash
In terminal 2, I connect to the socket with this Python code:
$ cat python-pass-unix-commands-socket.py
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('', 50007))
sock.send('ls\n')
data = sock.recv(1024)
print data
sock.close()
$ python pass-unix-commands-socket.py
This is the output I get in terminal 1 after running the command:
Ncat: Version 6.40 ( http://nmap.org/ncat )
Ncat: Listening on :::50007
Ncat: Listening on 0.0.0.0:50007
Ncat: Connection from 127.0.0.1.
Ncat: Connection from 127.0.0.1:39507.
$
And in terminal 2:
$ python pass-unix-commands-socket.py
alternating-characters.in
alternating-characters.rkt
angry-children.in
angry-children.rkt
angry-professor.in
angry-professor.rkt
$
I'm currently attempting to setup a SiriServer (that's beside the point) on Xubuntu 12.10 x64, when I run the server python returns error
socket.error: [Errno 98] Address already in use.
The server by default is attempting to run on port 443, which unfortunetly is required in order for this application to work.
To double check if anything is running on port 443, I execute the following:
lsof -i :443
There's no results, unless I have something like Chrome or Firefox open, which I end up closing. Here's the full return from attempting to run the server application.
dustin#dustin-xubuntu:~/Applications/SiriServer$ sudo python siriServer.py
CRITICAL load_plugins Failed loading plugin due to missing module: 'Wordnik library not found. Please install wordnik library! e.g. sudo easy_install wordnik'
INFO <module> Starting Server
Traceback (most recent call last):
File "siriServer.py", line 493, in <module>
server = SiriServer('', options.port)
File "siriServer.py", line 425, in __init__
self.bind((host, port))
File "/usr/lib/python2.7/asyncore.py", line 342, in bind
return self.socket.bind(addr)
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
I'm stuck on what to do, as this is the last part of setting up this application. Any help is appreciated.
You're not root -- that's your problem. To bind to ports under 1024 on Unix, you must be the superuser. So, hit su and try the python code again. Alternatively, bind to a port from 1024 to 65535.
This often happens when a python program doesn't exit properly when pressing ^C or ^Z. You could try reseting the terminal or exiting the terminal. You can also do killall -9 server.py
Another effective way to help prevent this even if you have root privs this can happen if a socket is not closed properly, here is a fix:
s=socket.socket( )
s.bind(("0.0.0.0", 8080))
while 1:
try:
c, addr = s.accept()
except KeyBoardInterrupt:
s.close()
exit(0)
I got that error even if port number is more than 1024
You can use
pkill -9 python
run command twice, it will list all python files which are killed
List all processes that you have running with
ps -a
Take the PID corresponding to python and pipe it into the kill command with (Example PID 2770)
kill -9 2770