На локальной машине все ок. Все отправляется на почту.
На удаленном серваке так
TimeoutError: [Errno 110] Connection timed out
Гугление пока результата не дало….
Кто может сталкивался с этим?
Как решали?
Last login: Tue May 24 09:59:29 2022 from 95.188.77.167
> root@templ-ubuntu-2004:~# cd /root/bots/ulya_bot2
> root@templ-ubuntu-2004:~/bots/ulya_bot2# python3.8 main.py
> FSM запущена
> подключил вторую часть
> РАБОТАЮ!
> executor.py [LINE:362] #INFO [2022-05-24 10:01:13,292] Bot: Juli_Key_bot [ @333t]
> executor.py [LINE:358] #WARNING [2022-05-24 10:01:14,379] Updates were skippe d successfully.
> Бот вышел онлайн
> Подключился к БД1
> dispatcher.py [LINE:358] #INFO [2022-05-24 10:01:14,381] Start polling.
> Valid email
> DataFrame:
> user_id name username e_mail phone
> 0 1284986166 Olga olga_viktorovna3335 jenya82333@inbox.ru 793333368
> base_events.py [LINE:1707] #ERROR [2022-05-24 10:03:51,235] Task exception was never retrieved
> future: <Task finished name='Task-47' coro=<Dispatcher._process_polling_update s() done, defined at /usr/local/lib/python3.8/dist-packages/aiogram/dispatcher/d ispatcher.py:407> exception=TimeoutError(110, 'Connection timed out')>
> Traceback (most recent call last):
> File "/usr/local/lib/python3.8/dist-packages/aiogram/dispatcher/dispatcher.p y", line 415, in _process_polling_updates
> for responses in itertools.chain.from_iterable(await self.process_updates( updates, fast)):
> File "/usr/local/lib/python3.8/dist-packages/aiogram/dispatcher/dispatcher.p y", line 235, in process_updates
> return await asyncio.gather(*tasks)
> File "/usr/local/lib/python3.8/dist-packages/aiogram/dispatcher/handler.py", line 116, in notify
> response = await handler_obj.handler(*args, **partial_data)
> File "/usr/local/lib/python3.8/dist-packages/aiogram/dispatcher/dispatcher.p y", line 256, in process_update
> return await self.message_handlers.notify(update.message)
> File "/usr/local/lib/python3.8/dist-packages/aiogram/dispatcher/handler.py", line 116, in notify
> response = await handler_obj.handler(*args, **partial_data)
> File "/root/bots/ulya_bot2/handlers/Partnerbase1.py", line 69, in get_phone
> await sqlite_db1.sql_add_command(state)
> File "/root/bots/ulya_bot2/data_base/sqlite_db1.py", line 43, in sql_add_com mand
> send_email(user, pwd, recipients, "Test Subject")
> File "/root/bots/ulya_bot2/data_base/sqlite_db1.py", line 38, in send_email
> server = smtplib.SMTP('smtp.jino.ru: 587')
> File "/usr/lib/python3.8/smtplib.py", line 255, in __init__
> (code, msg) = self.connect(host, port)
> File "/usr/lib/python3.8/smtplib.py", line 339, in connect
> self.sock = self._get_socket(host, port, self.timeout)
> File "/usr/lib/python3.8/smtplib.py", line 310, in _get_socket
> return socket.create_connection((host, port), timeout,
> File "/usr/lib/python3.8/socket.py", line 808, in create_connection
> raise err
> File "/usr/lib/python3.8/socket.py", line 796, in create_connection
> sock.connect(sa)
<b>> TimeoutError: [Errno 110] Connection timed out</b>
[2020-03-24 16:28:44,787: INFO/MainProcess] mingle: all alone
[2020-03-24 16:30:23,873: WARNING/MainProcess] consumer: Connection to broker lost. Trying to re-establish the connection...
Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/celery/worker/consumer/consumer.py", line 318, in start
blueprint.start(self)
File "/usr/local/lib/python3.7/site-packages/celery/bootsteps.py", line 119, in start
step.start(parent)
File "/usr/local/lib/python3.7/site-packages/celery/worker/consumer/consumer.py", line 599, in start
c.loop(*c.loop_args())
File "/usr/local/lib/python3.7/site-packages/celery/worker/loops.py", line 83, in asynloop
next(loop)
File "/usr/local/lib/python3.7/site-packages/kombu/asynchronous/hub.py", line 364, in create_loop
cb(*cbargs)
File "/usr/local/lib/python3.7/site-packages/kombu/transport/redis.py", line 1088, in on_readable
self.cycle.on_readable(fileno)
File "/usr/local/lib/python3.7/site-packages/kombu/transport/redis.py", line 359, in on_readable
chan.handlers[type]()
File "/usr/local/lib/python3.7/site-packages/kombu/transport/redis.py", line 693, in _receive
ret.append(self._receive_one(c))
File "/usr/local/lib/python3.7/site-packages/kombu/transport/redis.py", line 703, in _receive_one
response = c.parse_response()
File "/usr/local/lib/python3.7/site-packages/redis/client.py", line 3453, in parse_response
response = self._execute(conn, conn.read_response)
File "/usr/local/lib/python3.7/site-packages/redis/client.py", line 3427, in _execute
return command(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/redis/connection.py", line 734, in read_response
response = self._parser.read_response()
File "/usr/local/lib/python3.7/site-packages/redis/connection.py", line 316, in read_response
response = self._buffer.readline()
File "/usr/local/lib/python3.7/site-packages/redis/connection.py", line 248, in readline
self._read_from_socket()
File "/usr/local/lib/python3.7/site-packages/redis/connection.py", line 193, in _read_from_socket
raise ConnectionError(SERVER_CLOSED_CONNECTION_ERROR)
redis.exceptions.ConnectionError: Connection closed by server.
[2020-03-24 16:30:23,911: INFO/MainProcess] Connected to redis://redis:11535//
In any networking application, it’s common that one end will be trying to connect, while the other fails to respond due to a problem like a networking media failure. Fortunately, the Python socket library has an elegant method of handing these errors via the socket.error exceptions. Find out how to use them here.
How to do it
Let’s create a few try-except code blocks and put one potential error type in each block. In order to get a user input, the argparse module can be used. This module is more powerful than simply parsing command-line arguments using sys.argv. In the try-except blocks, put typical socket operations, for example, create a socket object, connect to a server, send data, and wait for a reply.
The following recipe illustrates the concepts in a few lines of code.
Listing 1.7 shows socket_errors as follows:
#!/usr/bin/env python
# Python Network Programming Cookbook — Chapter – 1
# This program is optimized for Python 2.7. It may run on any
# other Python version with/without modifications.
import sys
import socket
import argparse
def main():
# setup argument parsing
parser = argparse.ArgumentParser(description=’Socket Error Examples’)
parser.add_argument(‘—host’, action=»store», dest=»host», required=False)
parser.add_argument(‘—port’, action=»store», dest=»port», type=int, required=False)
parser.add_argument(‘—file’, action=»store», dest=»file», required=False)
given_args = parser.parse_args()
host = given_args.host
port = given_args.port
filename = given_args.file
# First try-except block — create socket
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error, e:
print «Error creating socket: %s» % e
sys.exit(1)
# Second try-except block — connect to given host/port
try:
s.connect((host, port))
except socket.gaierror, e:
print «Address-related error connecting to server: %s» % e
sys.exit(1)
except socket.error, e:
print «Connection error: %s» % e
sys.exit(1)
# Third try-except block — sending data
try:
s.sendall(«GET %s HTTP/1.0rnrn» % filename)
except socket.error, e:
print «Error sending data: %s» % e
sys.exit(1)
while 1:
# Fourth tr-except block — waiting to receive data from remote host
try:
buf = s.recv(2048)
except socket.error, e:
print «Error receiving data: %s» % e
sys.exit(1)
if not len(buf):
break
# write the received data
sys.stdout.write(buf)
if __name__ == ‘__main__’:
main()
How it works
In Python, passing command-line arguments to a script and parsing them in the script can be done using the argparse module. This is available in Python 2.7. For earlier versions of Python, this module is available separately in Python Package Index (PyPI). You can install this via easy_install or pip.
In this recipe, three arguments are set up: a hostname, port number, and filename. The usage of this script is as follows:
$ python 1_7_socket_errors.py –host=<HOST> —port=<PORT> —file=<FILE>
If you try with a non-existent host, this script will print an address error as follows:
$ python 1_7_socket_errors.py —host=www.pytgo.org —port=8080 —file=1_7_socket_errors.py
Address-related error connecting to server: [Errno -5] No address associated with hostname
If there is no service on a specific port and if you try to connect to that port, then this will throw a connection timeout error as follows:
$ python 1_7_socket_errors.py —host=www.python.org —port=8080 —file=1_7_socket_errors.py
This will return the following error since the host, www.python.org, is not listening on port 8080:
Connection error: [Errno 110] Connection timed out
However, if you send an arbitrary request to a correct request to a correct port, the error may not be caught in the application level. For example, running the following script returns no error, but the HTML output tells us what’s wrong with this script:
$ python 1_7_socket_errors.py —host=www.python.org —port=80 —file=1_7_socket_errors.py
HTTP/1.1 404 Not found
Server: Varnish
Retry-After: 0
content-type: text/html
Content-Length: 77
Accept-Ranges: bytes
Date: Thu, 20 Feb 2014 12:14:01 GMT
Via: 1.1 varnish
Age: 0
Connection: close
<html>
<head>
<title> </title>
</head>
<body>
unknown domain: </body></html>
In this example, four try-except blocks have been used. All blocks use socket.error except for the second one, which uses socket.gaierror. This is used for address-related errors. There are two other types of exceptions: socket.herror is used for legacy C API, and if you use the settimeout() method in a socket, socket.timeout will be raised when a timeout occurs on that socket.
This quick tip was taken from «Python Network Programming Cookbook» published by Packt. Network Computing readers can pick it up for free by clicking
here (which will automatically add the eBook to your cart) or by using the code RGPNPC50 at the checkout. The code expires Oct. 23, 2016. From October 10-16 you can save 50% on more Python ebooks by joining Packt for Python Week.
We’ve been seeing this periodically while deploying and sometimes more often:
2016-03-02 07:12:16 Service ‘glance’ does not need any more units added.
2016-03-02 07:12:16 Service ‘swift-storage’ does not need any more units added.
2016-03-02 07:12:16 Service ‘rabbitmq-server’ does not need any more units added.
2016-03-02 07:13:23 Config specifies num units for subordinate: ceilometer-agent
Traceback (most recent call last):
File «/usr/bin/juju-deployer», line 9, in <module>
load_entry_point(‘juju-deployer==0.6.2’, ‘console_scripts’, ‘juju-deployer’)()
File «/usr/lib/python2.7/dist-packages/deployer/cli.py», line 142, in main
run()
File «/usr/lib/python2.7/dist-packages/deployer/cli.py», line 241, in run
importer.Importer(env, deployment, options).run()
File «/usr/lib/python2.7/dist-packages/deployer/action/importer.py», line 431, in run
self.add_units()
File «/usr/lib/python2.7/dist-packages/deployer/action/importer.py», line 38, in add_units
env_status = self.env.status()
File «/usr/lib/python2.7/dist-packages/deployer/env/go.py», line 260, in status
return self.client.get_stat()
File «/usr/lib/python2.7/dist-packages/jujuclient.py», line 1049, in get_stat
watch = self.get_watch()
File «/usr/lib/python2.7/dist-packages/jujuclient.py», line 1075, in get_watch
watch_env = Environment(self.endpoint)
File «/usr/lib/python2.7/dist-packages/jujuclient.py», line 522, in __init__
self.conn = Connector.connect_socket(endpoint, self._ca_cert)
File «/usr/lib/python2.7/dist-packages/jujuclient.py», line 162, in connect_socket
endpoint, origin=endpoint, sslopt=sslopt)
File «/usr/lib/python2.7/dist-packages/websocket/_core.py», line 219, in create_connection
websock.connect(url, **options)
File «/usr/lib/python2.7/dist-packages/websocket/_core.py», line 438, in connect
self.sock.connect(address)
File «/usr/lib/python2.7/socket.py», line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 110] Connection timed out
These are current versions:
ii juju 1.25.3-0ubuntu1~14.04.1~juju1 all next generation service orchestration system
ii juju-core 1.25.3-0ubuntu1~14.04.1~juju1 amd64 Juju is devops distilled — client
ii juju-deployer 0.6.2.1-0ubuntu1~ppa1 amd64 A tool to deploy complex stacks of services using juju.
ii python-jujuclient 0.50.3+bzr69+30~ubuntu14.04.1 all Python API client for juju-core
Ubuntu Server 18.04
На VPS есть скрипт на Python3, который присылает мне емейлы.
Сегодня 01.02 не получил от него мейл, последний по плану был отправлен 26.01 успешно.
Начал разбираться, в логе запись:
Traceback (most recent call last):
Сначала подозреваю хостинг, выполняю их troubleshooting guide — всё работает, получаю тестовый мейл…
File "/home/ubuntu/reminder/reminder.py", line 57, in <module>
server = smtplib.SMTP(host)
File "/usr/lib/python3.6/smtplib.py", line 251, in __init__
(code, msg) = self.connect(host, port)
File "/usr/lib/python3.6/smtplib.py", line 336, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/usr/lib/python3.6/smtplib.py", line 307, in _get_socket
self.source_address)
File "/usr/lib/python3.6/socket.py", line 724, in create_connection
raise err
File "/usr/lib/python3.6/socket.py", line 713, in create_connection
sock.connect(sa)
TimeoutError: [Errno 110] Connection timed out
Там были команды такого типа
telnet email-smtp.eu-central-1.amazonaws.com 587
То есть соединение есть и сервис работает корректно.
telnet email-smtp.eu-central-1.amazonaws.com 465
openssl s_client -crlf -quiet -starttls smtp -connect email-smtp.eu-central-1.amazonaws.com:587 < input.txt
Ищу конкретную часть кода, на которой затык:
import smtplib
server = smtplib.SMTP("email-smtp.eu-central-1.amazonaws.com")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.6/smtplib.py", line 251, in __init__
(code, msg) = self.connect(host, port)
File "/usr/lib/python3.6/smtplib.py", line 336, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/usr/lib/python3.6/smtplib.py", line 307, in _get_socket
self.source_address)
File "/usr/lib/python3.6/socket.py", line 724, in create_connection
raise err
File "/usr/lib/python3.6/socket.py", line 713, in create_connection
sock.connect(sa)
TimeoutError: [Errno 110] Connection timed out
Это работает корректно на локальном ПК (другая версия Python).
import smtplib
server = smtplib.SMTP("email-smtp.eu-central-1.amazonaws.com")
server.quit()
(451, b'4.4.2 Timeout waiting for data from client.')
Уточняю про
/usr/lib/python3.6/socket.py
:
$ dpkg -S /usr/lib/python3.6/socket.py
libpython3.6-minimal:amd64: /usr/lib/python3.6/socket.py
Пакет обновлялся последний раз 28.11.19
Перезагрузка VPS не помогла.
Есть идеи?
Пользователь добавил сообщение 01 Февраля 2020, 11:42:18:
Фуф, разобрался.
Авторизация была вот такая, кривая, потому что раньше использовался smtp.gmail.com и он работал только так:
server = smtplib.SMTP(host)
server.connect(host, port)
server.ehlo()
server.starttls()
server.ehlo()
server.login(config.get("smtp", "login"), config.get("smtp", "password"))
Сейчас, очевидно, изменилась конфигурация текущего SMTP сервера, и эта кривизна больше не работает — хотя я должен был оставить себе комментарий и удалить её при уходе с gmail.
Правильный, рабочий, код выглядит так:
server = smtplib.SMTP(host, port)
server.starttls()
server.ehlo()
server.login(config.get("smtp", "login"), config.get("smtp", "password"))
A CentOS 7 web server has postfix, dovecot, and mailx installed. I have been able to make an IMAP connection to the server in order to read inbox mail using a remote Thunderbird client, but I am not able to make an SMTP connection to send email from Thunderbird. When I do forensics, I discover that the attempted SMTP connection times out. How can I resolve this problem of the connection timing out, so that I can send email from Thunderbird through the server?
My forensics so far have resulted in:
Typing hostname
in the terminal at the server returns mydomain.com
.
nano /usr/lib/firewalld/services/smtp.xml
indicates the smtp port is 25
The smtp service is activated in the public zone because firewall-cmd --list-all
results in:
public (default, active)
interfaces: enp3s0
sources:
services: dhcpv6-client imaps openvpn smtp
ports:
masquerade: yes
forward-ports:
icmp-blocks:
rich rules:
But when I try to telnet from my devbox to the remote CentOS 7 server, I get the following results. Typing telnet mydomain.com 25
resulted in:
Trying my.SERVER.ip.addr...
telnet: connect to address my.SERVER.ip.addr: Connection timed out
Then typing telnet smtp.mydomain.com 25
resulted in:
Trying my.SERVER.ip.addr...
telnet: connect to address my.SERVER.ip.addr: Connection timed out
Also, typing openssl s_client -CApath /etc/ssl/certs -starttls smtp -port 25 -host smtp.mydomain.com
results in:
socket: Connection timed out
connect:errno=110
Similarly, typing openssl s_client -CApath /etc/ssl/certs -starttls smtp -port 25 -host mydomain.com
also resulted in:
socket: Connection timed out
connect:errno=110
I typed nano /etc/postfix/main.cf
to start to examine the config, but did not find anything related to ports.
EDIT:
As per FaheemMitha’s advice, I tried telnet mydomain.com 587
from the client, and got No route to host
in reply. I think this is because only port 25 is open in firewalld for smtp.
I therefore thought to try telnet from within the remote server mydomain.com. When I logged on to my remote server via ssh and typed telnet localhost 25
, the result was:
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
220 mydomain.com ESMTP Postfix
This causes me to suspect that postfix is running on port 25, but that somehow it is not able to accept outside connections.
EDIT#2
As per @RedCricket’s suggestion, I ran iptables -L
. Since the results were verbose, I uploaded them to a file sharing site, which you can view by clicking on this link.
I also tried iptables --flush
followed by firewall-cmd --reload
, and then repeated the telnet and thunderbird tests from above, but I am still getting the connection timed out error.
What else can I try?
I uploaded the entire /etc/postfix/main.cf
to a file sharing site. You can read it by clicking on this link.
EDIT#3
A valid email address someone.else@some_other_domain.com sends email to me@mydomain.com without problems. Therefore, as a test, I had my remote Thunderbird client try to send email to that someone.else@some_other_domain.com as part of the work documented above in this OP. This morning, I received a return to sender message in my Thunderbird as a result of the test email. I interpret this returned message to mean that at least one of my test messages from Thunderbird got into the SMTP on mydomain.com, but that mydomain.com was not able to look up or otherwise connect to some_other_domain.com. Here is the message:
This is the mail system at host mydomain.com.
I'm sorry to have to someone.elserm you that your message could not
be delivered to one or more recipients. It's attached below.
For further assistance, please send mail to postmaster.
If you do so, please include this problem report. You can
delete your own text from the attached returned message.
The mail system
<someone.else@some_other_domain.com>: Host or domain name not found. Name service error for
name=some_other_domain.com type=MX: Host not found, try again
Reporting-MTA: dns; mydomain.com
X-Postfix-Queue-ID: 2C915811BD1C
X-Postfix-Sender: rfc822; me@mydomain.com
Arrival-Date: Mon, 23 Feb 2015 16:46:34 -0500 (EST)
Final-Recipient: rfc822; someone.else@some_other_domain.com
Action: failed
Status: 4.4.3
Diagnostic-Code: X-Postfix; Host or domain name not found. Name service error
for name=some_other_domain.com type=MX: Host not found, try again
ForwardedMessage.eml
Subject: key enclosed
From: me@mydomain.com
Date: 02/23/2015 01:46 PM
To: someone.else@some_other_domain.com
this is the body of the email
Thus, it seems that sometimes the connection from my remote devbox to mydomain.com is closed, and at other times, the connection from mydomain.com to the rest of the internet is closed.
EDIT#4
Following @derobert’s advice, I first tried the two telnet commands from the devbox to the server, then I tried to send an email from me@mydomain.com using the Thunderbird client on my devbox, and then I ran the tcpdump command on both the devbox and on the server. Typing tcpdump port 25
in the devbox terminal resulted in the following:
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on tun0, link-type RAW (Raw IP), capture size 65535 bytes
^C
0 packets captured
0 packets received by filter
0 packets dropped by kernel
Next, typing tcpdump
on the server resulted in so much output that the results scrolled endlessly until I typed Ctrl-C. So I then typed tcpdump port 25
and got the following results:
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on tun0, link-type RAW (Raw IP), capture size 65535 bytes
^C
0 packets captured
0 packets received by filter
0 packets dropped by kernel
As a curiosity, I then typed tcpdump port 25
again on both the devbox and the server simultaneously and left it open without typing Ctrl-C
, and I tried to manually send an email from me@mydomain.com using Thunderbird client on my devbox. I still got the same Connection timeout failure, but there was no activity reported by the open tcpdump port 25
commands. And the totals also came up to zero when I typed Ctrl-C
on both terminals afterwards.