Python Server running as a Windows Service doens't accept connexion - python

Most of all, my question is pretty similar to the following : Cannot access Python server running as Windows service. I tried the solution but it doesn't solve my problem.
I was able to connect a client and a server by using the Python Socket Tutorial :
# Echo server program
import socket
HOST = '' # Symbolic name meaning the local host
PORT = 50007 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
data = conn.recv(1024)
if not data: break
conn.send(data)
conn.close()
# Echo client program
import socket
HOST = 'daring.cwi.nl' # The remote host
PORT = 50007 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send('Hello, world')
data = s.recv(1024)
s.close()
print 'Received', repr(data)
and It worked like a charm, then I coded the following Windows Service :
import win32serviceutil
import win32service
import win32event
import servicemanager
import socket
import logging
import sys
class AppServerSvc (win32serviceutil.ServiceFramework):
_svc_name_ = "PySvc"
_svc_display_name_ = "PySvc"
_svc_description_ = "PySvc"
def __init__(self,args):
win32serviceutil.ServiceFramework.__init__(self,args)
self.hWaitStop = win32event.CreateEvent(None,0,0,None)
socket.setdefaulttimeout(60)
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
def SvcDoRun(self):
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_,''))
logging.basicConfig(filename='C:/test.log',
level =logging.DEBUG,
format ='%(asctime)s %(message)s',
filemode='w')
rc = None
self.HOST = '' # Symbolic name meaning the local host
self.PORT = 50007 # Arbitrary non-privileged port
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.s.bind((self.HOST, self.PORT))
logging.debug("BIND")
self.s.listen(1)
logging.debug("LISTENED")
self.conn, self.addr = self.s.accept()
logging.debug("ACCEPT")
logging.debug("connected to " + str(self.addr))
self.s.setblocking(1)
logging.debug("set blocking")
# if the stop event hasn't been fired keep looping
while rc != win32event.WAIT_OBJECT_0:
# block for 5 seconds and listen for a stop event
rc = win32event.WaitForSingleObject(self.hWaitStop, 5000)
self.main()
def main(self):
pass
if __name__ == '__main__':
win32serviceutil.HandleCommandLine(AppServerSvc)
But the connexion is never accepted by the service. the log contains :
2018-03-19 16:37:48,967 BIND
2018-03-19 16:37:48,967 LISTENED
If I do a netstat :
NETSTAT -an | find /i "listening"
I find the following line, which show that the server is listening :
TCP 0.0.0.0:50007 0.0.0.0:0 LISTENING
Can someone explain me why it doesn't work ?

Related

How to manually shutdown a socket server?

I have a simple socket server, how do I shut it down when I enter "shutdown" in the terminal on the server side?
import socket
SERVER = "xxxx"
PORT = 1234
ADDR = (SERVER, PORT)
FORMAT = "utf-8"
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)
def handle_connection(conn, addr):
...
server.listen()
while True:
conn, addr = server.accept()
handle_connection(conn, addr)
Close active connections and exit. It can be done with:
server.close()
exit(0)
To shutdown you socket server manually by calling server.close(), you whole code should be:
import socket
SERVER = "xxxx"
PORT = 1234
ADDR = (SERVER, PORT)
FORMAT = "utf-8"
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)
def handle_connection(conn, addr):
...
server.listen()
while True:
conn, addr = server.accept()
handle_connection(conn, addr)
# call server.close() to shut down your server.

How can I have an admin-client to remote shutdown server.py in a socket programming multiple clients?

So can someone please tell me how to have an admin-client shutting down the Server (server.py) in a socket multiple clients architecture? I want admin-client to type "shutdown" in client side then server will be shutdown. and right after submit, the server will call a function that shows network load graph . a graph with the number of requests per time slot.
Server:
`
import socket, threading
class ClientThread(threading.Thread):
def __init__(self,clientAddress,clientsocket):
threading.Thread.__init__(self)
self.csocket = clientsocket
print ("New connection added: ", clientAddress)
def run(self):
print ("Connection from : ", clientAddress)
#self.csocket.send(bytes("Hi, This is from Server..",'utf-8'))
msg = ''
while True:
data = self.csocket.recv(2048)
msg = data.decode()
if msg=='bye':
break
print ("from client", msg)
self.csocket.send(bytes(msg,'UTF-8'))
print ("Client at ", clientAddress , " disconnected...")
LOCALHOST = "127.0.0.1"
PORT = 8080
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind((LOCALHOST, PORT))
print("Server started")
print("Waiting for client request..")
while True:
server.listen(1)
clientsock, clientAddress = server.accept()
newthread = ClientThread(clientAddress, clientsock)
newthread.start()
Client:
import socket
SERVER = "127.0.0.1"
PORT = 8080
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((SERVER, PORT))
client.sendall(bytes("This is from Client",'UTF-8'))
while True:
in_data = client.recv(1024)
print("From Server :" ,in_data.decode())
out_data = input()
client.sendall(bytes(out_data,'UTF-8'))
if out_data=='bye':
break
client.close()
`
I have tried
if message == "shutdown":
close()
exit(0)
but dont know how to apply it

Can't tell if python server and client are interacting with each other

Have a client socket here that starts and connects but the receive function never runs or at least doesn't print. I get no errors in the console
import socket
from threading import Thread
MAX_BUFFER_SIZE = 4096
class ClientServer(Thread):
def __init__(self, HOST = "localhost", PORT = 8000):
print("Client Server started w/ new threads...")
Thread.__init__(self)
self.HOST = HOST
self.PORT = PORT
self.socket = None
def receive_from_Server(self):
print('Time to receive from Server.....')
result_bytes = self.socket.recv(MAX_BUFFER_SIZE)
result_string = result_bytes.decode("utf8")
print("Result from server is {}".format(result_string))
def start_server(self):
# Creates TCP socket
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Re-uses socket
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# Binds socket to host and port
self.socket.bind(("localhost", 8000))
def connect_server(self):
while True:
threads = []
# Become a server socket
print("Waiting for connections from TCP clients")
self.socket.listen(5)
# Starts connection
(clientSocket, client_address) = self.socket.accept()
newthread = ClientServer()
newthread.start()
threads.append(newthread)
for t in threads:
t.join()
cs = ClientServer()
cs.start_server()
cs.connect_server()
cs.receive_from_Server()
my client code here runs but again print doesn't print after I run this program and enter whatever message besides 'exit' as well as 'exit' not closing the client as well.
import socket
host = "localhost"
port = 8000
BUFFER_SIZE = 4096
MESSAGE = input("Client: Enter message and hit enter or 'exit' to end ")
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((host, port))
while MESSAGE != 'exit':
client.send(MESSAGE.encode("utf8"))
data = client.recv(BUFFER_SIZE)
print("Server received data:" + data)
MESSAGE = input("Client: Enter more or 'exit' to end ")
client.close()

Python - error when making a socket connection (server - target)

(Using Python 3) I am trying to connect server and client and symply send a message from one to another but I don't know why I get this strange error: OSError: [WinError 10057]. Does anyone know why it happened? I did a bit of reaserch but didn't find anything, I think I made an error when making global variables, or is it somenthing with message encoding and decoding?
Here is my full error:
File "server_side.py", line 34, in
shell()
File "server_side.py", line 6, in shell
s.send(command.encode('utf-8'))
OSError: [WinError 10057] A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a
sendto call) no address was supplied
Here is my server_side code:
import socket
def shell():
command = input('[+] Insert command: ')
s.send(command.encode('utf-8'))
message = target.recv(1024)
print(message.decode('utf-8'))
s = ''
target = ''
ip = ''
def server():
global s
global target
global ip
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)
s.bind(('192.168.1.109', 54321))#target ip, port more bit isti
s.listen(5)
print('[+] Listening for connections')
target, ip = s.accept()
print('[+] Connection established from: %s' %str(ip))
server()
shell()
And this is my client_side code:
import socket
def shell():
command = sock.recv(1024)
message = 'Hello there'
sock.send(message.encode('utf-8'))
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('192.168.1.109', 54321)) #home ip
shell()
sock.close()
My command input on server_side example vould be the word : Hello, or somenthing like that.
You have to put the shell() function in a infinite loop, and you have to run the server_side code and then the client_side code.
Here is a bit changed code:
Server side code:
import socket
def shell():
command = input('[+] Insert command: ')
s.send(command.encode('utf-8'))
message = target.recv(1024)
print(message.decode('utf-8'))
s = ''
target = ''
ip = ''
def server():
global s
global target
global ip
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)
s.bind(('192.168.1.109', 54321))#target ip, port more bit isti
s.listen(5)
print('[+] Listening for connections')
target, ip = s.accept()
print('[+] Connection established from: %s' %str(ip))
while True:
server()
shell()
s.close()
Client side code:
import socket
def shell():
command = sock.recv(1024)
message = 'Hello there'
sock.send(message.encode('utf-8'))
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('192.168.1.109', 54321)) #home ip
while True:
shell()
sock.close()

How do I connect to the internet through client's wifi? | Python

I've set up my server.py and client.py with the socket module, is there a way you can connect to the internet through the client? What i mean is, I want to have the server connect to the client through it's own internet, and then from there have the client use its internet to browse the web. But I have no idea how to do this.
So is there something I can leverage to achiece this?
Server:
import socket, threading
from time import sleep
PORT = 5430
SERVER = socket.gethostbyname(socket.gethostname())
ADDR = (SERVER, PORT)
FORMAT = 'utf-8'
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)
def handle_client(conn, addr):
print(f'[NEW CONNECTIONS] {addr} connected')
while True:
conn.recv(6000)
conn.close()
def start():
server.listen()
print(f'[LISTENING] Server is listening on {SERVER}')
while True:
conn, addr = server.accept()
thread = threading.Thread(target = handle_client, args = (conn,addr))
thread.start()
print(f'[ACTIVE CONNECTIONS] {threading.activeCount() - 1}')
print('[STARTNG] Server is starting')
start()
Client:
from time import sleep
import socket
PORT = 5430
SERVER = socket.gethostbyname(socket.gethostname())
FORMAT = 'utf-8'
ADDR = (SERVER, PORT)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(ADDR)
while True:
client.send('hi').encode(FORMAT)
conn.close()

Categories

Resources