pymongo.errors.ServerSelectionTimeoutError with atlas even when added to network access

Hello, I have been using pymongo with atlas for a while now, and suddenly around two hours ago, I must have done something wrong because the same code I’ve been using the entire time suddenly stopped working.

I have attempted to isolate the issue and made this reproducible example

from pymongo import MongoClient

client = MongoClient(
    "mongodb+srv://culturebot:[pass]@cluster0.whzdc.mongodb.net/culturebot?retryWrites=true&w=majority"
)
print(client.list_database_names())

and this is the full traceback

Traceback (most recent call last):
  File "C:\Users\D\code\thesadru\culturebot\_.py", line 6, in <module>
    print(client.list_database_names())
  File "C:\Users\D\AppData\Roaming\Python\Python39\site-packages\pymongo\mongo_client.py", line 1918, in list_database_names
    for doc in self.list_databases(session, nameOnly=True)]
  File "C:\Users\D\AppData\Roaming\Python\Python39\site-packages\pymongo\mongo_client.py", line 1899, in list_databases
    res = admin._retryable_read_command(cmd, session=session)
  File "C:\Users\D\AppData\Roaming\Python\Python39\site-packages\pymongo\database.py", line 755, in _retryable_read_command
    return self.__client._retryable_read(
  File "C:\Users\D\AppData\Roaming\Python\Python39\site-packages\pymongo\mongo_client.py", line 1460, in _retryable_read
    server = self._select_server(
  File "C:\Users\D\AppData\Roaming\Python\Python39\site-packages\pymongo\mongo_client.py", line 1278, in _select_serverer
    server = topology.select_server(server_selector)
  File "C:\Users\D\AppData\Roaming\Python\Python39\site-packages\pymongo\topology.py", line 241, in select_server
    return random.choice(self.select_servers(selector,
  File "C:\Users\D\AppData\Roaming\Python\Python39\site-packages\pymongo\topology.py", line 199, in select_servers
    server_descriptions = self._select_servers_loop(
  File "C:\Users\D\AppData\Roaming\Python\Python39\site-packages\pymongo\topology.py", line 215, in _select_servers_loop
    raise ServerSelectionTimeoutError(
pymongo.errors.ServerSelectionTimeoutError: cluster0-shard-00-02.whzdc.mongodb.net:27017: timed out,cluster0-shard-00-00.whzdc.mongodb.net:27017: timed out,cluster0-shard-00-01.whzdc.mongodb.net:27017: timed out, Timeout: 30s, Topology Description: <TopologyDescription id: 60f00e93a72f19041df4afa6, topology_type: ReplicaSetNoPrimary, servers: [<ServerDescription ('cluster0-shard-00-00.whzdc.mongodb.net', 27017) server_type: Unknown, rtt: None, error=NetworkTimeout('cluster0-shard-00-00.whzdc.mongodb.net:27017: timed out')>, <ServerDescription ('cluster0-shard-00-01.whzdc.mongodb.net', 27017) server_type: Unknown, rtt: None, error=NetworkTimeout('cluster0-shard-00-01.whzdc.mongodb.net:27017: timed out')>, <ServerDescription ('cluster0-shard-00-02.whzdc.mongodb.net', 27017) server_type: Unknown, rtt: None, error=NetworkTimeout('cluster0-shard-00-02.whzdc.mongodb.net:27017: timed out')>]>

The same error is raised even for other operations.

I have attempted to search around for a solution. Most of them consisted of using different parameters for the client or adding parameters to the query of the connection string, all of which yield the same result.

I have of course added both my IP and 0.0.0.0 to the network access.

Versions:

  • python 3.9.0
  • pymongo 3.11.4

Any directions would be appreciated, I can always provide more info.

1 Like
NetworkTimeout('cluster0-shard-00-01.whzdc.mongodb.net:27017: timed out')

This error means that pymongo timed out while waiting for a response from the remote server. Usually this means there is a network issue between your machine and the database.

  1. Could you provide the output to pip list?
  2. Could post the output of ping cluster0-shard-00-01.whzdc.mongodb.net?
  3. Could you try connecting with the mongodb shell?
2 Likes

I’ve been trying to connect using company wifi, excuse me for not knowing much about networking but I guess it’s because there’s some system in place that’d prevent me from connecting to addresses like these.
It seems to work completely fine when I’m at home for some reason.

output of `pip list` (there's a lot of modules installed)
absl-py                  0.13.0
aiohttp                  3.6.3
anime-downloader         5.0.7
animethemes-dl           2.2.2.3
appconfigpy              1.0.2
appdirs                  1.4.4
art                      5.1
astunparse               1.6.3
async-timeout            3.0.1
asyncio-dgram            2.0.0
atomicwrites             1.4.0
attrs                    20.3.0
Automat                  20.2.0
autopep8                 1.5.4
backcall                 0.2.0
bcrypt                   3.2.0
beartype                 0.5.1
beautifulsoup4           4.9.3
binary                   1.0.0
black                    21.6b0
bleach                   3.2.1
blinker                  1.4
boto3                    1.16.56
botocore                 1.19.56
Brotli                   1.0.9
browser-cookie3          0.12.1
browsermob-proxy         0.8.0
bs4                      0.0.1
bson                     0.5.10
CacheControl             0.12.6
cachetools               4.2.1
cachy                    0.3.0
certifi                  2020.12.5
cffi                     1.14.5
cfscrape                 2.1.1
chardet                  3.0.4
cleo                     0.8.1
click                    7.1.2
clikit                   0.6.2
cloudscraper             1.2.58
colorama                 0.4.4
coloredlogs              15.0
commonmark               0.9.1
constantly               15.1.0
crashtest                0.3.1
cryptography             3.3.1
cssselect                1.1.0
cv                       1.0.0
cycler                   0.10.0
Cython                   0.29.21
DataProperty             0.50.0
debtcollector            2.2.0
debugpy                  1.3.0
decorator                4.4.2
decouple                 0.0.7
deprecation              2.1.0
deskew                   0.10.32
discord                  1.0.1
discord-pretty-help      1.3.2
discord.py               1.7.2
discord.py-stubs         1.7.1
DiscordUtils             1.2.6
discum                   1.0.1
distlib                  0.3.2
dnspython                2.1.0
doc-search               1.0.7
docutils                 0.16
EditorConfig             0.12.3
envinfopy                0.0.3
excelrd                  2.0.3
eyeD3                    0.9.5
fake-useragent           0.1.11
fasttext                 0.9.2
feedparser               6.0.8
filelock                 3.0.12
filetype                 1.0.7
firebase-admin           4.5.2
Flask                    1.1.2
Flask-Cache              0.13.1
Flask-Caching            1.10.0
Flask-Cors               3.0.10
flask-swagger            0.2.14
flatbuffers              1.12
future                   0.18.2
fuzzywuzzy               0.18.0
gallery-dl               1.16.5
gast                     0.4.0
genshinstats             1.4.4.1
genshinstats-api         1.1
gmail                    0.6.3
google                   3.0.0
google-api-core          1.26.1
google-api-python-client 2.3.0
google-auth              1.27.1
google-auth-httplib2     0.1.0
google-auth-oauthlib     0.4.4
google-cloud-bigquery    2.13.0
google-cloud-core        1.6.0
google-cloud-firestore   2.0.2
google-cloud-storage     1.36.1
google-crc32c            1.1.2
google-pasta             0.2.0
google-resumable-media   1.2.0
googleapis-common-protos 1.53.0
googlemaps               4.4.5
googletrans              3.0.0
greenlet                 1.0.0
grpcio                   1.34.1
gunicorn                 20.0.4
h11                      0.9.0
h2                       3.2.0
h5py                     3.1.0
hpack                    3.0.0
hstspreload              2020.12.22
html2markdown            0.1.7
html5lib                 1.1
httpcore                 0.9.1
httplib2                 0.19.0
httpx                    0.13.3
humanfriendly            9.1
humanize                 3.7.0
hyperframe               5.2.0
hyperlink                21.0.0
idna                     2.8
imageio                  2.9.0
incremental              21.3.0
iniconfig                1.1.1
ipykernel                6.0.2
ipython                  7.25.0
ipython-genutils         0.2.0
iso8601                  0.1.13
itemadapter              0.2.0
itemloaders              1.0.4
itsdangerous             1.1.0
jedi                     0.18.0
jeepney                  0.6.0
Jinja2                   2.11.3
jmespath                 0.10.0
joblib                   1.0.1
Js2Py                    0.71
jsbeautifier             1.13.5
jsonpointer              2.1
jsonschema               3.2.0
jupyter-client           6.1.12
jupyter-core             4.7.0
kaitaistruct             0.9
Keras                    2.4.3
keras-nightly            2.5.0.dev2021032900
Keras-Preprocessing      1.1.2
keyboard                 0.13.5
keyring                  21.5.0
kiwisolver               1.3.1
lockfile                 0.12.2
loguru                   0.5.3
lxml                     4.6.3
lz4                      3.1.3
Mako                     1.1.4
mando                    0.6.4
Markdown                 3.3.3
MarkupSafe               1.1.1
matplotlib               3.4.2
matplotlib-inline        0.1.2
mbstrdecoder             1.0.1
mcstatus                 6.1.0
mechanize                0.4.5
mock                     4.0.3
motor                    2.4.0
MouseInfo                0.1.3
msgfy                    0.1.0
msgpack                  1.0.2
multidict                4.7.6
mutagen                  1.45.1
mypy                     0.800
mypy-extensions          0.4.3
mysql                    0.0.2
mysql-connector-python   8.0.23
mysqlclient              2.0.3
nbformat                 5.0.8
netaddr                  0.8.0
netifaces                0.11.0
networkx                 2.5.1
nltk                     3.6.2
numpy                    1.21.1
oauth2client             4.1.3
oauthlib                 3.1.0
opencv-python            4.5.1.48
opt-einsum               3.3.0
orjson                   3.5.2
os-service-types         1.7.0
oslo.i18n                5.0.1
packaging                20.9
pandas                   1.2.0
parse                    1.19.0
parsel                   1.6.0
parso                    0.8.2
pastel                   0.2.1
path                     15.0.1
path.py                  12.5.0
pathspec                 0.8.1
pathvalidate             2.3.1
pbkdf2                   1.3
pbr                      5.6.0
pdoc3                    0.9.2
peewee                   3.13.3
pexpect                  4.8.0
phonenumbers             8.12.21
pickleshare              0.7.5
Pillow                   8.1.0
pip                      21.1.3
pip-check-reqs           2.2.0
pkginfo                  1.6.1
plotly                   5.1.0
pluggy                   0.13.1
poetry                   1.1.6
poetry-core              1.0.3
praw                     7.2.0
prawcore                 2.0.0
priority                 1.3.0
prompt-toolkit           3.0.18
Protego                  0.1.16
proto-plus               1.14.2
protobuf                 3.15.5
psutil                   5.8.0
ptyprocess               0.7.0
py                       1.10.0
pyaes                    1.6.1
pyasn1                   0.4.8
pyasn1-modules           0.2.8
PyAutoGUI                0.9.52
pybind11                 2.7.0
PyBluez                  0.23
pycana                   0.1
pycodestyle              2.6.0
pycparser                2.20
pycryptodome             3.10.1
pycryptodomex            3.9.9
pydantic                 1.8.2
PyDispatcher             2.0.5
pydivert                 2.1.0
PyDrive                  1.3.1
pyee                     8.1.0
pyfiglet                 0.8.post1
pygame                   2.0.1
PyGetWindow              0.0.9
Pygments                 2.8.1
pyjsparser               2.7.1
pylev                    1.4.0
pymongo                  3.12.0
PyMsgBox                 1.0.9
PyMySQL                  1.0.2
PyNaCl                   1.4.0
pynput                   1.7.3
pyOpenSSL                20.0.1
pyparsing                2.4.7
pyperclip                1.8.1
pypinfo                  19.0.0
pyppeteer                0.2.5
PyQt5                    5.15.2
PyQt5-sip                12.8.1
pyquery                  1.4.3
pyreadline               2.1
pyreadline3              3.3
PyRect                   0.1.4
pyrsistent               0.17.3
PyScreeze                0.1.26
PySimpleGUI              4.39.1
pySmartDL                1.3.4
PySocks                  1.7.1
pytablereader            0.30.1
pyte                     0.8.0
pytesseract              0.3.8
pytest                   6.2.3
python-brainfuck         0.9.1
python-dateutil          2.8.1
python-gmaps             0.3.1
python-Levenshtein       0.12.1
pytube                   10.8.4
PyTweening               1.0.3
pytz                     2020.5
PyWavelets               1.1.1
pywin32                  300
pywin32-ctypes           0.2.0
PyYAML                   5.1
pyzmq                    22.1.0
queuelib                 1.5.0
radon                    5.0.1
random-user-agent        1.0.1
rapidfuzz                1.0.0
readme-renderer          28.0
regex                    2020.11.13
requests                 2.25.1
requests-cache           0.5.2
requests-html            0.10.0
requests-oauthlib        1.3.0
requests-toolbelt        0.9.1
requestsexceptions       1.4.0
retryrequests            0.0.3
rfc3986                  1.4.0
rich                     9.11.0
rsa                      4.7.2
s3transfer               0.3.4
scikit-image             0.18.2
scikit-learn             0.24.2
scipy                    1.5.4
Scrapy                   2.5.0
seaborn                  0.11.1
SecretStorage            3.3.1
selenium                 3.141.0
selenium-wire            4.0.4
sentry-sdk               0.19.4
service-identity         18.1.0
setuptools               56.0.0
sgmllib3k                1.0.0
shellingham              1.4.0
SimpleSQLite             1.1.4
six                      1.15.0
sniffio                  1.2.0
soupsieve                2.1
spotdl                   3.6.1
spotipy                  2.18.0
SQLAlchemy               1.4.12
sqlitebiter              0.34.1
sqliteschema             1.0.5
stevedore                3.3.0
stockfish                3.13.0
tabledata                1.1.3
tabulate                 0.8.7
tcolorpy                 0.0.8
tenacity                 8.0.1
tensorboard              2.5.0
tensorboard-data-server  0.6.1
tensorboard-plugin-wit   1.8.0
tensorflow               2.5.0
tensorflow-estimator     2.5.0
termcolor                1.1.0
thefuck                  3.30
threadpoolctl            2.2.0
tifffile                 2021.7.2
tinydb                   4.4.0
tinyrecord               0.2.0
toml                     0.10.2
tomlkit                  0.7.2
tornado                  6.1
tox                      3.23.1
tqdm                     4.56.0
traitlets                5.0.5
twine                    3.3.0
Twisted                  21.2.0
twisted-iocpsupport      1.0.1
typed-ast                1.4.2
typeguard                2.12.1
typepy                   1.1.2
typing-extensions        3.7.4.3
tzlocal                  2.1
ua-parser                0.10.0
ujson                    4.0.2
Unidecode                1.2.0
update-checker           0.18.0
uritemplate              3.0.1
urllib3                  1.26.4
virtualenv               20.4.7
w3lib                    1.22.0
wcwidth                  0.2.5
webencodings             0.5.1
websocket-client         0.57.0
websockets               8.1
Werkzeug                 1.0.1
wheel                    0.36.2
win-unicode-console      0.5
win32-setctime           1.0.3
wrapt                    1.12.1
wsproto                  1.0.0
XlsxWriter               1.4.0
yarl                     1.5.1
youtube-dl               2021.5.16
ytmusicapi               0.14.3
zipp                     3.4.1
zope.interface           5.3.0

When I ping the cluster:

> ping cluster0-shard-00-01.whzdc.mongodb.net

Pinging ec2-18-196-119-49.eu-central-1.compute.amazonaws.com [18.196.119.49] with 32 bytes of data:
Reply from 18.196.119.49: bytes=32 time=19ms TTL=39
Reply from 18.196.119.49: bytes=32 time=19ms TTL=39
Reply from 18.196.119.49: bytes=32 time=19ms TTL=39
Reply from 18.196.119.49: bytes=32 time=19ms TTL=39

Ping statistics for 18.196.119.49:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 19ms, Maximum = 19ms, Average = 19ms

I installed the mongo shell and attempted to connect to the cluster, still got a timeout after ~30s

> mongosh cluster0-shard-00-01.whzdc.mongodb.net

Current Mongosh Log ID: 60f7ca8b2aae42386b38edb3
Connecting to:          mongodb://cluster0-shard-00-01.whzdc.mongodb.net:27017/test?directConnection=true
MongoServerSelectionError: connect ETIMEDOUT 18.196.119.49:27017
2 Likes

Hi, Make sure you entered the user password, not the MongoDB account password. I encountered similar issue.

1 Like

I’m having the same issue. Is there no solution for this? I tried to do what @shane told and got the same results as @sadru.

This thread is 2 months old.

Please start a new thread and post a screenshot of what you are trying that shows the issue you are having.

If you could not resolve your issue with what was posted in this thread, then your issue is slightly different and should be on its own thread.

I am going through the same problem recently. Did you get any solution to this issue?

1 Like

As already mentioned

Now 3 months, and more since the original message.

As already mentioned

As already mentioned

Hello, buddy.
I had this problem before, so i have tried everything to solve it and i did.
So, most probably you added your own ip adress when you were creating a db, but you need to allow all the ip adresses that will connect to your db.
You may change it in your page in network access.
Thank you for attention! :slightly_smiling_face:
I hope it will be useful for you.

21 Likes

Couldn’t connect with enabled VPN (ProtonVPN). Works without it.

1 Like

@sadru Go to Mongo db atlas dashboard
Select your current project
click on Network Access (left side menu)
In the “IP Access List” tab
Make sure you don’t have an old dynamic IP of your machine set there
Or you can add 0.0.0.0/0 (includes your current IP address) to access from anywhere

7 Likes

This worked for me, thanks you so much

1 Like

You’re the most generous Lord in all the Land, thank you sir :slightly_smiling_face:

Thx bro you are a truly god

Another solution-
I created a SCRAM user in the database access tab.
Then, I added &authSource=the_database&authMechanism=SCRAM-SHA-1 to the connection string. Like this:

connect_string = 'mongodb+srv://{}:{}@{}/?retryWrites=true&authSource=the_database&authMechanism=SCRAM-SHA-1'.format(username, password, hostname)
py_client = MongoClient(connect_string)

I asked a team member in chat and they gave a working answer!

This is what they said:
If you are receiving an SSL certificate error when connecting to your Atlas cluster with PyMongo, such as:

  • unable to get local issuer certificate
  • [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed

This indicates that Python does not have access to the system’s root certificates.

This often occurs because OpenSSL does not have access to the system’s root certificates or the certificates are out of date. Linux users should ensure that they have the latest root certificate updates installed from their Linux vendor.

A sample command script is included in “/Applications/Python <version_number>” to install a curated bundle of default root certificates from the third-party certifi package. Open a terminal window and run the following command, with your Python version.

open "/Applications/Python <version_number>/Install certificates.command"

Alternatively, you can head to the Applications folder in Finder and double click “Install Certificates.command” to run the script:

6 Likes

I logged in to thanks you very much :slight_smile:

Not sure how special it is but for me it works by replacing the url with mongodb+srv://:@cluster0.gr4blbt.mongodb.net/?ssl=true&ssl_cert_reqs=CERT_NONE&retryWrites=true&w=majority

Basically adding ssl=true&ssl_cert_reqs=CERT_NONE and remove the “?” in the end

ssl_cert_reqs=CERT_NONE is insecure and not recommended. See ServerSelectionTimeoutError [SSL: CERTIFICATE_VERIFY_FAILED] Trying to understand the origin of the problem for how to fix TLS errors securely.

2 Likes


I am facing this issue can anyone help me out