Connect to Socket on localhost - python

I have trouble connecting to my own socket on localhost.
s.connect(('127.0.0.1', 4458)) (or "localhost") will just take forever,
and eventually timeout with TimeoutError: [Errno 110] Connection timed out
It should open port 4458, another script will then send some chars to it. Both scripts are supposed to run on the same Raspberry Pi, while 'server' one will execute with sudo (to access the GPIOs) and one without, being a chat bot.
I have no trouble running the server on the Pi (with python 3.4.1) and the client on my Laptop (mac, python 3.4.2).
Also it does work in reverse direction, server script on the laptop and client on the Raspberry.
As final test, it works with both, the server and the client on the said macbook.
Just server + client on the Pi does not work.
The program freezes
My shortened code if it helps:
# $ sudo python3 server.py
__author__ = 'luckydonald'
import socket # server
import time # wait for retry
import threading
class Server(threading.Thread):
port = 4458;
QUIT = False
def run(self):
s = socket.socket()
failed = True
print ("Starting Server on Port %d" % (self.port))
while failed:
try:
s.bind(("", self.port))
except Exception as err:
print(err)
print("Port assignment Failed. Retring in 1 second.")
time.sleep(1)
else:
failed = False
print("Success.")
while not self.QUIT:
print("Listening!")
conn, addr = s.accept() # freezes here
print("Got something: %s , %s" %(str(conn), str(addr)))
while not self.QUIT:
result = conn.recv(1)
print("Got result: " + str(result))
server = Server();
server.daemon = True
server.run();
# server.start();
And for the client:
# python3 cilent.py
s = socket.socket()
print("connecting...")
s.connect(("localhost",4458)) # also tried "172.0.0.1" # freezes here
print("connected!")
s.sendall("+".encode("utf-8"))
s.sendall("-".encode("utf-8"))
s.close()
It will result in this:

What I didn't expected was that localhost/127.0.0.1 did not work.
100% package loss
I had a malformatted entry in my hosts file.

You should check for below items
there is an installed internet information services
iis is running
firewall is grants required ports for running the python.exe

Related

How to create Python API or network requests hidden (protected from hackers checking network traffic) on Local Network to manage Computers

I know that I can see inside of network traffic for example with WireShark. When i use GET on HTML I can see those stuff in URL, what should not be problem what I am doing. But I believe GET,POST and maybe REQUEST too, as I did not work with that one yet can bee seen on something like Wire Shark network analyzer.
I am making Python client, what i will put on computers in network to show their IP,Host Name and Users on PC. This client will be as gate to the computer for remote control. As our management does not want to spend money for windows server, or other management system we need to get something free to manage all computers.
I am also seeking advice how I could do it as you are more skilled then me here.
I found few ways.
With the client create SSH Gateway for receiving commands.
With Client enable the Powershell remote option, then just push scripts to all computers at once.
Use some way the API requests etc... I am not skilled in this one at all, but I believe this is the way how other similar programs works?
As this client would create big security risk, I am first seeking way what is best way to hide it from network. Probably I will need to come up with some Private and public Key system here as well.
What are yours suggestions please on this topic?
here is just very short code I am playing with to receive basic info as IP, Host name and all Users
the Flask website showing those values is just for test, It will not be there once it is deployed
Update
I took advice from MarulForFlask but I got a couple issues. First this i think can have only one connection at a time. And second if possible Can i get the output of console from the client PC on screen of Server PC?
I want this output only for testing, as I know if i do something like netstat or any other command with multiple clients it would filled up screen with too many text... Currently I am getting back text format as plaintext with \r \n ... and other text deviders.
I am now trying Multicast, but i am getting error for binding the multicast IP.
OSError: [WinError 10049] The requested address is not valid in its context
Master.py
import time
import socket
import sys
import os
valueExit = True
# Initialize s to socket
s = socket.socket()
# Initialize the host
host = socket.gethostname()
BUFFER_SIZE = 1024
# Initialize the port
port = 8080
# Bind the socket with port and host
s.bind(('', port))
print("waiting for connections...")
# listening for conections
s.listen()
# accepting the incoming connections
conn, addr = s.accept()
print(addr, "is connected to server")
def send_query():
keepAllive, repeatIt = True, False
print("""To exit session write: EndSession
For help write: help
""")
while (keepAllive == True):
# commands for server use only
innerCommands = ["endsession", "help"]
# take command as input
command = input(str("Enter Command : "))
if command not in innerCommands:
conn.send(command.encode())
print("Command has been sent successfully.")
keepAllive = False
repeatIt = True
elif (command == "endsession"):
conn.send(command.encode())
valueExit = False
elif (command == "help"):
print("""To exit session write: EndSession""")
while (repeatIt == True):
# recieve the confrmation
data = conn.recv(BUFFER_SIZE)
if data:
print(f"command recieved and executed sucessfully.\n {data}")
keepAllive = True
repeatIt = False
else:
print("No reply from computer")
keepAllive = True
repeatIt = False
while valueExit == True:
send_query()
Slave.py
import time
import socket
import sys
import subprocess
import os
stayOn = True
def establishConnection():
# Initialize s to socket
s = socket.socket()
# Initialize the host
host = "127.0.0.1"
# Initiaze the port
port = 8080
keepAlive = True
try:
# bind the socket with port and host
s.connect((host, port))
print("Connected to Server.")
while keepAlive == True:
# recieve the command from master program
command = s.recv(1024)
command = command.decode()
# match the command and execute it on slave system
if command == "endsession":
print("Program Ended")
keepAlive = False
elif command != "":
# print("Command is :", command)
#s.send("Command recieved".encode())
proc = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)
(out, err) = proc.communicate()
s.send(f"{out}".encode())
print("program output:", out)
except Exception as err:
print(f"Error: {err}")
s.send(f"Error: {err}".encode())
while stayOn == True:
establishConnection()
see:
https://www.pythonforthelab.com/blog/how-to-control-a-device-through-the-network/
There uses a flask webserver.
otherwise, create a master.py file and paste this code:
import time
import socket
import sys
import os
# Initialize s to socket
s = socket.socket()
# Initialize the host
host = socket.gethostname()
# Initialize the port
port = 8080
# Bind the socket with port and host
s.bind(('', port))
print("waiting for connections...")
# listening for conections
s.listen()
# accepting the incoming connections
conn, addr = s.accept()
print(addr, "is connected to server")
# take command as input
command = input(str("Enter Command :"))
conn.send(command.encode())
print("Command has been sent successfully.")
# recieve the confrmation
data = conn.recv(1024)
if data:
print("command recieved and executed sucessfully.")
open a slave.py and paste this code:
import time
import socket
import sys
import os
# Initialize s to socket
s = socket.socket()
# Initialize the host
host = "127.0.0.1"
# Initiaze the port
port = 8080
# bind the socket with port and host
s.connect((host, port))
print("Connected to Server.")
# recieve the command from master program
command = s.recv(1024)
command = command.decode()
# match the command and execute it on slave system
if command == "open":
print("Command is :", command)
s.send("Command recieved".encode())
# you can give batch file as input here
os.system('ls')
open slave.py in client, master.py in server
https://www.geeksforgeeks.org/how-to-control-pc-from-anywhere-using-python/

Reconnecting a Bluetooth device using socket library (RFCOMM mode) in python 3?

I am trying to connect to a Bluetooth GPS unit from a Raspberry Pi3 using the socket library in python 3. I am able to connect and get data flowing the first time but if I disconnect and then try reconnecting I get:
[Errno 16] Device or resource busy
I have tried placing the connection in a sub process killing it and recreating it (end goal) and I get the same error. If I close and restart the test program it connects no problem.
Here is a test script based on a demo I found, that opens the connection closes it then tries to reconnect for ever. When I try it I get tick tick tick... until I hit ^c to kill it
import io
import socket
from time import sleep
from bluetooth import *
import sys
class SocketIO(io.RawIOBase):
def __init__(self, sock):
self.sock = sock
def read(self, sz=-1):
if (sz == -1): sz=0x7FFFFFFF
return self.sock.recv(sz)
def seekable(self):
return False
# file: l2capclient.py
# desc: Demo L2CAP client for bluetooth module.
# $Id: l2capclient.py 524 2007-08-15 04:04:52Z albert $
if sys.version < '3':
input = raw_input
if len(sys.argv) < 2:
print("usage: l2capclient.py <addr>")
sys.exit(2)
bt_addr=sys.argv[1]
port = 1
print("trying to connect to %s on PSM 0x%X" % (bt_addr, port))
# Create the client socket
sock=BluetoothSocket( RFCOMM )
sock.connect((bt_addr, port))
fd = SocketIO(sock)
bno = 0
for line in fd:
print(line)
bno +=1
if bno >10:
break
sock.shutdown(socket.SHUT_RDWR)
sock.close()
print("closed")
sock=BluetoothSocket( RFCOMM )
not_connected = True
while not_connected:
try:
sock.connect((bt_addr, port))
not_connected = False
except:
sleep(1)
print("tick")
pass
fd = SocketIO(sock)
try:
for line in fd:
print(line)
except IOError:
pass
sock.close()
The SocketIO class is just for convenience of getting data line by line I have tried it with sock.recv(1024) and got the same results.
I have a similar issue. I send data to an HC-05 bluetooth module from my PC using python sockets and a bluetooth RFCOMM socket. Here are a few things which have seemed to improve the debugging situation working with bluetooth...
If you havent already, make your socket a nonblocking socket, it sends out a flag when something goes wrong instead of crashing the program
Make sure you close the connection properly (it seems that you are doing that though)
Make sure that the GPS has no factory settings that prevent you from connecting instantly again. It could maybe have to do with a factory setting/timeout thing not agreeing with the way you request to connect again, and that error could be due to your code and quite possibly in a factory setting if there are any.

Execute python script on remote server from another script

import os
import sys
import commands
os.system('cat disk_space.py | ssh niraj#abc python - "sys.argv[1]"')
O/P:
python: No match.
Any idea ?
Directly run python script in your server, listen some one port which is not be used. when the port receive a signal, run the script which you want execute.
How to create socket service:
def tcplink(sock, addr):
print('Accept new connection from %s:%s...' % addr)
sock.send(b'Welcome!')
while True:
data = sock.recv(1024)
time.sleep(1)
if not data or data.decode('utf-8') == 'exit':
break
# execute what you want
sock.close()
print('Connection from %s:%s closed.' % addr)
Keep service alive in your server.

Errno 111: Connection refused only in python IDLE

When I try to execute Python server socket program and client socket program (both running in same linux machine) in Linux terminal I don't get any error, server accepts connection and sends data to client successfully.
But when I execute the same programs in python IDLE I get "[Errno 111] Connection refused" error.
What is the difference in both execution?
I'm using serversock.bind(('',port#)) in server
and in client i'm using clientsock.connect(('localhost',port#))
Server.py
import socket
serversock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host = ''
print host
port = 5800
serversock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
serversock.bind((host,port))
serversock.listen(2)
try:
while True:
csock,addr = serversock.accept()
print 'Recieved address from %s '% str(addr)
csock.send('hello')
csock.close()
except Exception,e:
print e
client.py
import socket
try:
c = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host = 'localhost'
port = 5800
c.connect((host,port))
data = c.recv(1024)
print data
except Exception,e:
print e
finally:
c.close()
Server side you must use:
serversock.bind(('',port#)) # binds to port
serversock.listen(5) # actually listen to port and allow 5 incoming calls
conv = serversock.accept() # accept first incoming call
The connection will only be accepted after the listen call, before it, you have only bound a socket, but have not declared that you were ready to accept incoming calls, so they are refused.
With added code, another possible error cause is that you close connection (server side) immediately after sending data. That is bad: the close condition can destroy the socket before the data has actually been sent.
You should use a graceful shutdown:
server side:
csock.send('hello')
csock.shutdown(socket.SHUT_WR) # shutdown the socket
csock.read() # wait the close from peer
csock.close()
client side: you can leave the code as is in your use case you do not send anything to server, so when the client has finished reading it can safely close the socket
Anyway you should close serversock when everything is finished
try:
...
except ...:
...
finally:
serversock.close()

PyBluez not accepting connection

I'm trying to setup a RFCOMM client-server communication system between my PC and my Nokia E63. I'm using Python with PyBluez for setting up the server and using PyS60 to program the client on my phone.
However PyBluez is not accepting the connection.
Here the code for the server:
from bluetooth import *
server_sock=BluetoothSocket( RFCOMM )
server_sock.bind(("",PORT_ANY))
server_sock.listen(1)
port = server_sock.getsockname()[1]
uuid = "94f39d29-7d6d-437d-973b-fba39e49d4ee"
advertise_service( server_sock, "SampleServer",
service_id = uuid,
service_classes = [ uuid, SERIAL_PORT_CLASS ],
profiles = [ SERIAL_PORT_PROFILE ],
# protocols = [ OBEX_UUID ]
)
print "Waiting for connection on RFCOMM channel %d" % port
client_sock, client_info = server_sock.accept()
print "Accepted connection from ", client_info
try:
while True:
data = client_sock.recv(1024)
if len(data) == 0: break
print "received [%s]" % data
except IOError:
pass
print "disconnected"
client_sock.close()
server_sock.close()
print "all done"
And here is the code for the client
#!/usr/bin/env python
import socket
class BTReader:
def connect(self):
self.sock=socket.socket(socket.AF_BT, socket.SOCK_STREAM)
addr, services=socket.bt_discover()
print "Discovered: %s, %s" % (addr, services)
port = services[services.keys()[0]]
print port
address=(addr,port)
print "Connecting to", str(address), "..."
self.sock.connect(address)
print "OK."
data = "Hello, World!"
print "Sending data:", data
self.sock.send("Hello World!");
print "SENT."
def close(self):
self.sock.close()
def main():
bt=BTReader()
bt.connect()
bt.close()
if __name__ == '__main__':
main()
When I run both the programs I get this output
1) Server (PC):
Waiting for connection on RFCOMM channel 1 [And it stays there. It doesn't acknowledge the connection. I've checked using WINPDB, even after the phone shows that it has established a connection, the server script remains in the server_sock.accept() loop.]
2) Client (phone):
Discoverd: xx:xx:xx:xx:xx:xx {u'SampleServer':1}
1
Connecting to ('xx:xx:xx:xx:xx:xx', 1) ...
OK.
Sending data: Hello World!
Traceback (most recent call last):
...
...
File "c;\resource\socket.py" , line 409, in send return self._sock.send(data, f, cb)
error: (0, 'Error')
What is causing the problem ??
I know its a year later, but I have another solution. On certain versions of Debian (Raspbian etc) and maybe some others distros. The server_sock.accept() will by default just hang and never accept a connection - even from a paired device! However, a solution to this is really simple. If you go to /etc/bluetooth/main.conf there is a line which is called Disable Plugins. Add a line or change so it looks like this:-
DisablePlugins = pnat
Then restart the Bluetooth service:-
sudo invokeā€“rc.d bluetooth restart
It now MAY have been fixed.
Good luck!
Reference: RFCOMM without pairing using PyBluez on Debian?
You should re-read the Rfcomm-client.py example of the PyBluez library.
I don't know why you are using some random socket instead of the BluetoothSocket object...
However I suspect that is the error. To detail for further readers:
If you look at the client code, he was importing the socket module and using that - that has NOTHING to do with pybluez and is wrong.
As a hint, try to make the 2 examples in the PyBluez library work (client and server) and then make your application.
Sometimes the server pops a window and asks the user to approve the connection. If you run without an X-server then you don't have the chance to see the dialog window and the connection is refused..!! (have spent half a day in the past on this...!!!)

Categories