Why won't my flask server bind my ip address? - python

I have tried running from localhost, 0.0.0.0, and from my ipv4 address.
When I used localhost, I could not access my server from another computer.
When I used 0.0.0.0, I had the same problem, and when I used my public ipv4 address it threw an error.
My code:
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run(host="[my ip address]")
my error:
* Serving Flask app "hello" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
Traceback (most recent call last):
File "hello.py", line 14, in <module>
app.run(host="[my ip address]")
File "/home/boomerhackr/.local/lib/python3.6/site-packages/flask/app.py", line 990, in run
run_simple(host, port, self, **options)
File "/home/boomerhackr/.local/lib/python3.6/site-packages/werkzeug/serving.py", line 1052, in run_simple
inner()
File "/home/boomerhackr/.local/lib/python3.6/site-packages/werkzeug/serving.py", line 1005, in inner
fd=fd,
File "/home/boomerhackr/.local/lib/python3.6/site-packages/werkzeug/serving.py", line 848, in make_server
host, port, app, request_handler, passthrough_errors, ssl_context, fd=fd
File "/home/boomerhackr/.local/lib/python3.6/site-packages/werkzeug/serving.py", line 740, in __init__
HTTPServer.__init__(self, server_address, handler)
File "/usr/lib/python3.6/socketserver.py", line 456, in __init__
self.server_bind()
File "/usr/lib/python3.6/http/server.py", line 136, in server_bind
socketserver.TCPServer.server_bind(self)
File "/usr/lib/python3.6/socketserver.py", line 470, in server_bind
self.socket.bind(self.server_address)
OSError: [Errno 99] Cannot assign requested address
To find my ip address I used the bash command curl ifconfig.me.
my OS:
NAME="Ubuntu"
VERSION="18.04.4 LTS (Bionic Beaver)"
Is this a problem with Ubuntu, or with my code?

The best way to tackle this would be to have the following:
app.run(host='0.0.0.0', port='8000') where port could be changed as per convenience.
When you use app.run without any parameters, it defaults to host as 127.0.0.1 it binds to your local system. In this state, your application cannot be connected via any other system either through LAN or WAN (public address)
When you run it using 0.0.0.0 it's accessible both via LAN as well as WAN. To get your LAN Address in Ubuntu, you could simply run hostname -I and for WAN Address as mentioned, you could use curl ifconfig.me. So, you can access your application from another system on the same LAN by using LAN_IP:PORT
Now, most of the ISP's do not provide a static IP and you cannot expose your WAN IP on the internet. However, when you run the application using 0.0.0.0 on a VPS you could directly use the server's WAN IP and connect.
For your reference, the difference between 127.0.0.1 and 0.0.0.0 can be found here

"curl ifconfig.me" give you your public IP address. Sometimes it is assigned to a router and in several cases the LAN use NAT. That means that you computer could has a private IP address. Did you verify the addresses assigned on your interfaces with the command ifconfig ?

Related

Unable to connect to Redis instance running on Azure Linux VM from Python

I created an Ubuntu VM on Azure. In its inbound networking filters, I added ports 22 (for SSHing) and 6379 (for Redis). Following this, I SSHed into an instance from my bash shell, downloaded, built and installed Redis from source. The resultant redis.conf file is located in /tmp/redis-stable, so I edited that to comment out the bind 127.0.0.1 rule.
Then I started redis-server redis.conf from the /tmp/redis-stable directory, and it started normally, following which I SSHed into another instance of the VM, started redis-cli and set some keys. Retrieved them, working correctly.
Now in Python I am running this command:
r = redis.Redis(host='same_which_I_use_for_SSHing', port=6379, password='pwd')
It connects immediately (looks weird). But then when I try a simple command like r.get("foo"), I get this error:
>>> r.get("foo")
Traceback (most recent call last):
File "/lib/python3.5/site-packages/redis/connection.py", line 484, in connect
sock = self._connect()
File "/lib/python3.5/site-packages/redis/connection.py", line 511, in _connect
socket.SOCK_STREAM):
File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/socket.py", line 732, in getaddrinfo
for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno 8] nodename nor servname provided, or not known
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/lib/python3.5/site-packages/redis/client.py", line 667, in execute_command
connection.send_command(*args)
File "/lib/python3.5/site-packages/redis/connection.py", line 610, in send_command
self.send_packed_command(self.pack_command(*args))
File "/lib/python3.5/site-packages/redis/connection.py", line 585, in send_packed_command
self.connect()
File "/lib/python3.5/site-packages/redis/connection.py", line 489, in connect
raise ConnectionError(self._error_message(e))
redis.exceptions.ConnectionError: Error 8 connecting to username#ip_address. nodename nor servname provided, or not known.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/lib/python3.5/site-packages/redis/connection.py", line 484, in connect
sock = self._connect()
File "/lib/python3.5/site-packages/redis/connection.py", line 511, in _connect
socket.SOCK_STREAM):
File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/socket.py", line 732, in getaddrinfo
for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno 8] nodename nor servname provided, or not known
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/lib/python3.5/site-packages/redis/client.py", line 976, in get
return self.execute_command('GET', name)
File "/lib/python3.5/site-packages/redis/client.py", line 673, in execute_command
connection.send_command(*args)
File "/lib/python3.5/site-packages/redis/connection.py", line 610, in send_command
self.send_packed_command(self.pack_command(*args))
File "/lib/python3.5/site-packages/redis/connection.py", line 585, in send_packed_command
self.connect()
File "/lib/python3.5/site-packages/redis/connection.py", line 489, in connect
raise ConnectionError(self._error_message(e))
redis.exceptions.ConnectionError: Error 8 connecting to username#ip_address. nodename nor servname provided, or not known.
Any idea how to fix this? FYI, the username#ip_address in the error message is the same I use for SSH from bash and connecting to Redis from Python respectively:
ssh username#ip_address
r = redis.Redis(host='username#ip_address', port=6379, password='pwd')
I also tried adding bind 0.0.0.0 in the redis.conf file after commenting out the bind 127.0.0.1 line. Same result.
Update: I tried setting protected mode to no in the config file, followed by running sudo ufw allow 6379 in the VM. Still same result. But now I get a weird error when I run redis-server redis.conf. I don't get the typical redis cube which shows up as a figure Instead I get this:
After this, if I enter redis-cli and issue a simple command like set foo boo, I get this error message:
127.0.0.1:6379> set foo 1
(error) MISCONF Redis is configured to save RDB snapshots, but it is currently not able to persist on disk. Commands that may modify the data set are disabled, because this instance is configured to report errors during writes if RDB snapshotting fails (stop-writes-on-bgsave-error option). Please check the Redis logs for details about the RDB error.
Even shutdown fails after this. I have to run grep to find the process if of redis-server and kill it manually, following which redis-server command needs to be run to start it normally. But of course, I still cannot connect from remote Mac.
I tried to create an Ubuntu VM on Azure, build & configure redis server from source code, and add a port rule for my VM NSG on Azure portal, then I connected the redis server via the same code with python redis package successfully.
Here is my steps as below.
Create an Ubuntu 18.04 VM on Azure portal.
Connect the Ubuntu VM via SSH to install the build packages (include build-essential, gcc and make), download & decompress the tar.gz file of redis source code from redis.io, and build & test the redis server with make & make test.
Configure the redis.conf via vim, to change the bind configuration from 127.0.0.1 to 0.0.0.0.
Add a new port rule of 6379 port with TCP into the NSG for the Network Interface shown in the tab Settings -> Networking of my VM on Azure portal, as the figures below.
Notes: There are two NSG in my Networking tab, the second one is related to my Network Interface which can be accessed via internet.
and
5. Install redis via pip install redis on my local machine.
6. Open a termial to type python to try to connect the redis server hosted on my Azure Ubuntu VM and get the value of the foo key successfully.
>>> import redis
>>> r = redis.Redis(host='xxx.xx.xx.xxx')
>>> r.get('foo')
b'bar'
There are two key issues I found within my testing.
For redis.conf, the binding host must be 0.0.0.0. If not, redis server will be running in protected mode to refuse the query.
For the NSG port rules, make sure the new port rule added in the NSG attached to the current network interface, not the default subnet.
The python package redis is lazy evaluation, only connect redis server when first command request happened.
Hope it helps.

Python ftplib - Errno 10061- No connection could be made because the target machine actively refused it

I want to establish a FTP connection to Windows server (let's say 10.20.30.50)
I am using Python ftblib package
session = ftplib.FTP('10.20.30.40','admin','password#123')
file = open('download.jpg','rb') # file to send
session.storbinary('STOR download.jpg', file) # send the file
file.close() # close file and FTP
session.quit()
But I am getting the error
socket.error: [Errno 10061] No connection could be made because the target machine actively refused it
Traceback:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\ftplib.py", line 120, in __init__
self.connect(host)
File "C:\Python27\lib\ftplib.py", line 135, in connect
self.sock = socket.create_connection((self.host, self.port), self.timeout)
File "C:\Python27\lib\socket.py", line 571, in create_connection
raise err
socket.error: [Errno 10061] No connection could be made because the target machine actively refused it.
I tried telnet 10.20.30.40 8081 and it is successful.
I allow port 8081 for ftp. I open port by adding new inbound rules.
I tried several available solutions on Stack Overflow as well as other sites but they all are talking about to check the port. I do all the things but still no help.
Thanks
If your FTP server uses a non-standard port (8081), you have to specify that, when using FTP class.
session = ftplib.FTP()
session.connect('10.20.30.40', 8081)
session.login('admin','password#123')
See also Python ftplib - specify port.
I forgot to enable FTP service in server. I followed this link and it is solved my issue
https://medium.com/#JohGeoCoder/allowing-ftp-access-on-windows-server-2016-hosted-on-microsoft-azure-af25898df958

Bottle python program runs in dev environment but not in live environment

I am trying to get python bottle application running, but for some reason it fails. I am using bottle 0.13 and python 2.7 on cent os 7.2 version.
The same program runs in dev environment which has centos 6.7 but not in live environment. I get the following stack trace:
File "helloworld.py", line 7, in <module>run(host='localhost', port=8080)
File "/bottle.py", line 3127, in run server.run(app) File "/bottle.py", line 2781, in run
srv = make_server(self.host, self.port, app, server_cls, handler_cls)
File "/usr/lib64/python2.7/wsgiref/simple_server.py", line 144, in make_server
server = server_class((host, port), handler_class)
File "/usr/lib64/python2.7/SocketServer.py", line 420, in _init_self.server_activate()
File "/usr/lib64/python2.7/SocketServer.py", line 439, in server_activate
self.socket.listen(self.request_queue_size)
File "/usr/lib64/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)socket.error: [Errno 98] Address already in use
Any help will be appreciated.
Looks like there is already a process listening on port 8080. You can use the follow command to check who is using 8080:
lsof -i :8080
To change the port, edit port=8080 parameter to some other port and rerun application:
run(host='localhost', port=8080)

how to run django sslserver(https) such that remote systems in network can also access?

I am trying to run my server with https, so I installed django-sslserver, and running as below.
python manage.py runsslserver --certificate /etc/ssl/certs/server.crt --key /etc/ssl/private/server.key 0.0.0.0:8000
It is running successfully with above command. I am able to access through localhost:8000 or 127.0.0.1:8000, but not able to access through 192.168.2.13:8000 here 192.168.2.13 is my IP address.
Why I am not able to access through my IP address ?
And even If start the server with other than 8000 port, it is default taking as 8000. Here in the below example I have used 8014, But its taking 8000 as default.
root#nagapavan-HP-ProBook-440-G2:/home/nagapavan/Downloads/celestial_NAS# python manage.py runsslserver --certificate /etc/ssl/certs/server.c --key /etc/ssl/private/server.key 127.0.0.1:8014
Validating models...
System check identified some issues:
WARNINGS:
NAS.UserProfile.user: (fields.W342) Setting unique=True on a ForeignKey has the same effect as using a OneToOneField.
HINT: ForeignKey(unique=True) is usually better served by a OneToOneField.
System check identified 1 issue (0 silenced).
October 06, 2015 - 13:21:40
Django version 1.8.4, using settings 'celestial_NAS.settings'
Starting development server at 127.0.0.1:8000/
Using SSL certificate: /etc/ssl/certs/server.crt
Using SSL key: /etc/ssl/private/server.key
Quit the server with CONTROL-C
Why it is taking the port number 8000 as default?
I found one more command to start server as below. I can give the IP address and port number. It is working as as expected. But I am able to access with the IP address but not able to access through localhost:9000 or 127.0.0.1:9000 even I am accessing the server my local system itself.
What might be the reason for above statement?
And even I am able to access through my IP address with https://192.168.2.13:9000, I am not able to access the server from remote system which is in the same network(even pingable to each other)
Why I am not able to access the server from remote system in the same network, Do we need to do any configuration file changes?
python manage.py runsslserver --certificate /etc/ssl/certs/server.c --key /etc/ssl/private/server.key --addrport 192.168.2.13:9000
Note: All the URIs above accessed with https
Adding the error which I am getting while starting sslserver as below:
Is it the reason of issues above?
----------------------------------------
----------------------------------------
Exception happened during processing of request from ('192.168.1.166', 56694)
Traceback (most recent call last):
File "/usr/lib/python2.7/SocketServer.py", line 295, in _handle_request_noblock
self.process_request(request, client_address)
File "/usr/lib/python2.7/SocketServer.py", line 321, in process_request
self.finish_request(request, client_address)
File "/usr/lib/python2.7/SocketServer.py", line 334, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "/usr/local/lib/python2.7/dist-packages/django/core/servers/basehttp.py", line 102, in __init__
super(WSGIRequestHandler, self).__init__(*args, **kwargs)
File "/usr/lib/python2.7/SocketServer.py", line 649, in __init__
self.handle()
File "/usr/local/lib/python2.7/dist-packages/django/core/servers/basehttp.py", line 167, in handle
self.raw_requestline = self.rfile.readline(65537)
File "/usr/lib/python2.7/socket.py", line 476, in readline
data = self._sock.recv(self._rbufsize)
File "/usr/lib/python2.7/ssl.py", line 341, in recv
return self.read(buflen)
File "/usr/lib/python2.7/ssl.py", line 260, in read
return self._sslobj.read(len)
SSLError: [Errno 1] _ssl.c:1429: error:14094418:SSL routines:SSL3_READ_BYTES:tlsv1 alert unknown ca
----------------------------------------
----------------------------------------
Its working kindly use instead of 0.0.0.0 try your network ip,and allow on host add network ip

redis.exceptions.ConnectionError: Error -2 connecting to localhost:6379. Name or service not known

I have this error when I run my code in server, my env is debian, and Python2.7.3
Traceback (most recent call last):
File "fetcher.py", line 4, in <module>
import mirad.fetcher_tasks as tasks
File "/home/mirad/backend/mirad/fetcher_tasks.py", line 75, in <module>
redis_keys = r.keys('*')
File "/home/mirad/backend/venv/local/lib/python2.7/site-packages/redis/client.py", line 863, in keys
return self.execute_command('KEYS', pattern)
File "/home/mirad/backend/venv/local/lib/python2.7/site-packages/redis/client.py", line 534, in execute_command
connection.send_command(*args)
File "/home/mirad/backend/venv/local/lib/python2.7/site-packages/redis/connection.py", line 532, in send_command
self.send_packed_command(self.pack_command(*args))
File "/home/mirad/backend/venv/local/lib/python2.7/site-packages/redis/connection.py", line 508, in send_packed_command
self.connect()
File "/home/mirad/backend/venv/local/lib/python2.7/site-packages/redis/connection.py", line 412, in connect
raise ConnectionError(self._error_message(e))
redis.exceptions.ConnectionError: Error -2 connecting to localhost:6379. Name or service not known.
when I run redis-cli it works correctly without any error:
$ redis-cli
127.0.0.1:6379>
It seems that you are trying connect redis with server that is unidentified by your current Debian environment.
From Traceback, I see you are trying to connect using host name as localhost ,
r_server=redis.Redis(host="localhost",port=6379)
But , your system is unable to understand "localhost" , make entry in hosts file i.e saying 127.0.0.1 is localhost. add below code in /etc/hosts
127.0.0.1 localhost
otherwise connect redis using below command ;
r_server=redis.Redis(host="127.0.0.1",port=6379)
I faced a similar problem and later on realized that I have not opened redis in the terminal by command: $ redis-server.
Maybe it is the case.

Categories

Resources