How to connect to main Flask APP from a remote server - python

import psutil
STATS_URL = ' http://172.20.10.2:8080/report'
SERVER_NAME="test_local_server"
def get_health():
print('generating health report')
cpu_percent = psutil.cpu_percent(interval=2.0)
ctime = psutil.cpu_times()
disk_usage = psutil.disk_usage("/")
net_io_counters = psutil.net_io_counters()
virtual_memory = psutil.virtual_memory()
# The keys in this dict should match the db cols
report = dict (
USER_NAME="USER",
SERVER_NAME="Test_Server",
cpupercent = cpu_percent,
cpu_total = ctime.user + ctime.system,
free_Percnt=((disk_usage.free/disk_usage.used)*100),
bytes_sent = net_io_counters.bytes_sent,
bytes_received = net_io_counters.bytes_recv,
packets_sent = net_io_counters.packets_sent,
packets_received = net_io_counters.packets_recv,
memory_Free = virtual_memory.free,
)
return report
if __name__=='__main__':
print(f'starting health report stream for server :\t{SERVER_NAME}')
while True:
report = get_health()
r = requests.post(STATS_URL, json=report)
time.sleep(20)
I need to send the values of this script which is on an AWS remote server back to my Flask APP which is my main server on my windows laptop.
#app.route("/report",methods=['POST'])
def report():
if request.method=='POST':
time_epoch=time.time()
incoming_report = request.get_json()
print("Generating Health report")
username=incoming_report["USER_NAME"]
server_name=incoming_report["SERVER_NAME"]
disk_free=incoming_report["free_Percnt"]
bytes_sent=incoming_report["bytes_sent"]
bytes_received=incoming_report["bytes_received"]
packets_sent=incoming_report["packets_sent"]
packets_received=incoming_report["packets_received"]
memory_free=incoming_report["memory_Free"]
cpu_percent=incoming_report["cpupercent"]
cpu_total=incoming_report["cpu_total"]
conn=sqlite3.connect("Health.db")
conn.execute(f"create table if not exists {username}_{server_name}
(HEALTH_ID integer primary key AUTOINCREMENT,Time_Epoch integer,Disk_Free varchar(80),Bytes_Sent varchar(80),Bytes_Received varchar(80),Packets_Sent varchar(80),Packets_Received varchar(80),Memory_Free varchar(80),Cpu_Usage_Percent varchar(80),Cpu_Time varchar(80));")
conn.execute(f'insert into {username}_{server_name} (Time_Epoch,Disk_Free,Bytes_Sent,Bytes_Received,Packets_Sent,Packets_Received,Memory_Free,Cpu_Usage_Percent,Cpu_Time) values {time_epoch,disk_free,bytes_sent,bytes_received,packets_sent,packets_received,memory_free,cpu_percent,cpu_total}')
conn.commit()
return {'message': 'success'}
if __name__ ==("__main__"):
app.run(host='0.0.0.0',port=8080)
So i changed the host to '0.0.0.0' cause when i checked online thats what i found to make the flask app public but the connection from script says connection timed out.Can someone please help me send the values from the python script back to my flask app?

You need to forward port 8080 on your router. Right now your home router is also a firewall and doesn't permit anything initiating a connection with a LAN machine (your PC). It needs to be told "if anyone tries to connect to our home IP at port 8080, connect it to my PC at the internal IP x.x.x.x"

Related

Python function to check if still alive

I am running 2 python scripts: one server script and one client(both Windows 10),who connects to the server.
If for example the connection is lost because the client system restarts and the python script does have autorun by startup, how can I reconnect? Because when I do not restart the server it has an error when the client restarted.
Is there a function or trick someone knows to check if the clients script is still running(so I can remotely restart the server)? Or even beter something that doesn't let the server have a connection error if the client system restarts.
shown: simple python chatroom
SERVER
import time, socket, sys
new_socket = socket.socket()
host_name = socket.gethostname()
s_ip = socket.gethostbyname(host_name)
port = 8080
new_socket.bind((host_name, port))
print( "Binding successful!”)
print("This is your IP: ", s_ip)
name = input('Enter name: ')
new_socket.listen(1)
conn, add = new_socket.accept()
print("Received connection from ", add[0])
print('Connection Established. Connected From: ',add[0])
client = (conn.recv(1024)).decode()
print(client + ' has connected.')
conn.send(name.encode())
while True:
message = input('Me : ')
conn.send(message.encode())
message = conn.recv(1024)
message = message.decode()
print(client, ':', message)
CLIENT
import time, socket, sys
socket_server = socket.socket()
server_host = socket.gethostname()
ip = socket.gethostbyname(server_host)
sport = 8080
print('This is your IP address: ',ip)
server_host = input('Enter friend\'s IP address:')
name = input('Enter Friend\'s name: ')
socket_server.connect((server_host, sport))
socket_server.send(name.encode())
server_name = socket_server.recv(1024)
server_name = server_name.decode()
print(server_name,' has joined...')
while True:
message = (socket_server.recv(1024)).decode()
print(server_name, ":", message)
message = input("Me : ")
socket_server.send(message.encode())
You must create a multithread server. In a multithread server, a new independent thread (separated from the main thread) is created for each client.
So, when your client stops, the server finishes only the client's thread, while the main thread keeps running, waiting for new clients.
There are plenty of examples of multithread servers in web. Here are a few examples:
https://www.geeksforgeeks.org/socket-programming-multi-threading-python/
How to make a simple multithreaded socket server in Python that remembers clients
https://www.positronx.io/create-socket-server-with-multiple-clients-in-python/

Amazon web services: server-client connection with local machine using python socket ip address setting

I have started using amazon web services for creating server. I need to communicate my local machine with aws server.
What ip-address should I set in the following python scripts.
Server side:
import socket
def server_program():
# get the hostname
host = "172.17.130.197"
port = 5588
server_socket = socket.socket()
server_socket.bind((host, port))
server_socket.listen(2)
conn, address = server_socket.accept() # accept new connection
print("Connection from: " + str(address))
while True:
data = conn.recv(1024).decode()
print("from connected user: " + str(data))
d=str(data)
data = d.upper()
conn.send(data.encode()) # send data to the client
conn.close() # close the connection
if __name__ == '__main__':
server_program()
Client side:
import socket
def Main():
host = "172.17.130.197"
port = 5590
mySocket = socket.socket()
mySocket.connect((host,port))
message = input(" -> ")
while message != 'q':
mySocket.send(message.encode())
data = mySocket.recv(1024).decode()
print ('Received from server: ' + data)
message = input(" -> ")
mySocket.close()
if __name__ == '__main__':
Main()
Please help, thanks in advance.
Please check if your instance has public IP assigned. When you select the server IPv4 Public IP and Public DNS (IPv4) indicate if your instance is accessible from the outside world. If so - this is the IP and FQDN you can reach your instance. You probably need to open the communication port in relevant security group (AWS autoamtically creates default SG).
If you don't have any values there you need to create ElasticIP.
Go to EC2 -> Network & Security -> Elastic IPs
Create new EIP
Attach the IP to the instance
Add the communication port to the security group (which is default if you don't create it manually)
The IP provided should appear on details of the instance

How to deploy gRPC server/client to heroku?

I deployed my python gRPC server to Heroku and was wondering how I could test it with a local Python client.
server.py
def serve():
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
icp_pb2_grpc.add_MyServicer_to_server(MyServicer(), server)
server_port = os.environ.get('PORT', 50051)
server.add_insecure_port('[::]:'+ str(server_port))
server.start()
print("==== SERVER RUNNING =====")
try:
while True:
time.sleep(_ONE_DAY_IN_SECONDS)
except KeyboardInterrupt:
server.stop(0)
if __name__ == '__main__':
serve()
client.py
def run():
# Is the channel url correct?
channel = grpc.insecure_channel('https://www.HEROKUURL.com:50051')
stub = my_grpc.MyStub(channel)
file = _get_file_content()
response = stub.Predict(icp_pb2.MyRequest(file_content=file))
print("received: " + response.results)
I am using the client from my computer and am not receiving any response from the server. I am able to successfully communicate with the server if it is launched locally. What am I doing wrong?
Heroku does not support HTTP 2. On the other hand, GRPC uses a http/2 based transport. I think that's why you can connect it locally but not from Heroku.

Python multiple threaded servers running in the same program

So I am currently writing a python server for a small game. I am currently trying to have the program run two servers in threads. From testing I have found a small bump in my process and that is that only one server is running at a time. I am using different ports for each of the servers however the one connected first takes dominance.
Server code snippets:
class loginServer(socketserver.BaseRequestHandler):
def handle(self):
# self.request is the TCP socket connected to the client
self.data = self.request.recv(1024).strip()
sent = str(self.data,'ascii').split(":")
print("login:\t\t",sent)
if (sent[0] == "l"):
#login check
#cur.execute("SELECT password, userid FROM `prototb` WHERE username = '"+sent[1]+"'")
cur.execute("SELECT `displayname`,`curmap`,`curpos`,`Inventory`,`abilities`,`password`,`userid` FROM `prototb` WHERE username = '"+sent[1]+"'")
plyInfo = cur.fetchone()#get the information from the database
if (plyInfo != None):#if the account doesnt exist the username is wrong
if (plyInfo[5] == sent[2]):#check the correctness of the password
print("Login-Success:\t",plyInfo)
send = pickle.dumps([plyInfo[1],plyInfo[2],plyInfo[3],plyInfo[4],plyInfo[5]])
else:
self.request.send(bytes("-", 'ascii'))#refuse entry (bad password)
else:
self.request.send(bytes("-", 'ascii'))#refuse entry (bad username)
def run_loginServer():
HOST, PORT = "localhost", 9000
# Create the server, binding to localhost on port 9000
server = socketserver.TCPServer((HOST, PORT), loginServer)
# Activate the server; this will keep running until you
# interrupt the program with Ctrl-C
server.serve_forever()
And for the other server thread:
class podListener(socketserver.BaseRequestHandler):
def handle(self):
# self.request is the TCP socket connected to the client
self.data = self.request.recv(1024).strip()
sent = str(self.data,'ascii').split(":")
print("pods:\t\t",sent)
if (sent[0] == "l"):
maps[mapNum][0] = sent[1]
maps[mapNum][1] = self.client_address[0]
maps[mapNum][2] = sent[2]
print("Pod Connected:\t",maps[mapNum])
#send confirmation
self.request.send(bytes("+", 'ascii'))
else:
print("Pod Failed connection: ", self.client_address[0])
def run_podListener():
HOST, PORT = "localhost", 9001
# Create the server, binding to localhost on port 9001
server = socketserver.TCPServer((HOST, PORT), podListener)
# Activate the server; this will keep running until you
# interrupt the program with Ctrl-C
server.serve_forever()
Then I run this to start them both:
if __name__ == "__main__":
#get the database handle
run_dbConnect()
#run the map pod server
run_podLauncher()
#run the login server ### localhost 9000
run_loginServer()
The client works connecting to them separately, when I comment out the threads individually, but never together. Any help will be greatly appreciated.

python ftp server showing "150 File status okay. About to open data connection." and does nothing

I am trying to run an ftp server in python using pyftpdlib module. The problem occurring is that it shows a "150 File status okay. About to open data connection." and then just stays like that forever until the server time's out.
I log in through cmd , using the ftp command.
PLs help.
Here is the server code:
import os
import sqlite3
from pyftpdlib import ftpserver
def main():
authorizer = ftpserver.DummyAuthorizer()
ftp_auth_table="H:\\ftp_auth_table1.db"
connection=sqlite3.connect(ftp_auth_table,isolation_level=None)
cursor=connection.cursor()
cursor.execute('''SELECT * FROM ftp_auth_table1''')
entry=cursor.fetchall()
# change os.gtcwd() with ftp_actv_dir
for x in entry:
authorizer.add_user(x[1], x[2], "H:/MS EVERYTHING", perm='elradfmwM')
# Instantiate FTP handler class
handler = ftpserver.FTPHandler
handler.authorizer = authorizer
handler.banner = "pyftpdlib %s based ftpd ready." %ftpserver.__ver__
address = ('127.0.0.1', 21)
ftpd = ftpserver.FTPServer(address, handler)
ftpd.max_cons = 256
ftpd.max_cons_per_ip = 5
# start ftp server
ftpd.serve_forever()
if __name__ == '__main__':
main()
I predict, with absolute confidence, that you'll find the problem is due to the space between "MS EVERYTHING".

Categories