在启动或关闭期间运行的 Python 脚本中名称解析暂时失败

在启动或关闭期间运行的 Python 脚本中名称解析暂时失败

我编写了一个 Python 脚本,它通过 Telegram 发送任何消息:

#!/opt/anaconda3/bin/python

import asyncio
import telegram
import os
import sys


async def main():
    bot = telegram.Bot(os.environ["TELEGRAM_TOKEN"])
    async with bot:

        #print(await bot.get_me())
        #print((await bot.get_updates())[0])
        await bot.send_message(text=' '.join(sys.argv[1:]), chat_id=MYCHATID)


if __name__ == '__main__':
    asyncio.run(main())

TELEGRAM_TOKEN设置在 中/etc/environmentMYCHATID是硬编码的。

创建了两个脚本来运行它

# cat /etc/init.d/sendbot_boot.sh
#!/bin/bash

/opt/anaconda3/bin/python /usr/local/bin/sendbot "Booting..."

# cat /etc/init.d/sendbot_shutdown.sh
#!/bin/bash

/opt/anaconda3/bin/python /usr/local/bin/sendbot "Shutting down..."

将其中之一添加到cron

# cat /var/spool/cron/crontabs/root
@reboot /etc/init.d/sendbot_boot.sh

还有另一张到rc6

# ls -l /etc/rc6.d/K99sendbot_shutdown
lrwxrwxrwx 1 root root 29 фев 10 02:08 /etc/rc6.d/K99sendbot_shutdown -> ../init.d/sendbot_shutdown.sh

所有脚本都是可执行的,并且当我从终端运行它们时运行良好。但它们在实际重启时都不起作用。

我做错了什么?

# lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 18.04.6 LTS
Release:        18.04
Codename:       bionic

我已经抓取了错误输出并得到:

Traceback (most recent call last):
  File "/opt/anaconda3/lib/python3.8/site-packages/httpcore/_exceptions.py", line 10, in map_exceptions
    yield
  File "/opt/anaconda3/lib/python3.8/site-packages/httpcore/backends/asyncio.py", line 111, in connect_tcp
    stream: anyio.abc.ByteStream = await anyio.connect_tcp(
  File "/opt/anaconda3/lib/python3.8/site-packages/anyio/_core/_sockets.py", line 189, in connect_tcp
    gai_res = await getaddrinfo(
  File "/opt/anaconda3/lib/python3.8/site-packages/anyio/_core/_sockets.py", line 496, in getaddrinfo
    gai_res = await get_asynclib().getaddrinfo(
  File "/opt/anaconda3/lib/python3.8/site-packages/anyio/_backends/_asyncio.py", line 1754, in getaddrinfo
    result = await get_running_loop().getaddrinfo(
  File "/opt/anaconda3/lib/python3.8/asyncio/base_events.py", line 825, in getaddrinfo
    return await self.run_in_executor(
  File "/opt/anaconda3/lib/python3.8/concurrent/futures/thread.py", line 57, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/opt/anaconda3/lib/python3.8/socket.py", line 918, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno -3] Temporary failure in name resolution

答案1

看起来脚本在重新启动时无法正确执行。在 Ubuntu 18.04 上, /etc/rcX.d/ 目录中的系统服务和脚本由程序执行/sbin/runlevel。中的初始化脚本/etc/init.d/可以直接执行,但它们还必须链接到适当的/etc/rcX.d/目录,以便在引导时或更改运行级别时执行。

尝试使用以下命令在相应的 rcX.d 目录中为 init 脚本创建符号链接:

sudo ln -s /etc/init.d/sendbot_boot.sh /etc/rc2.d/S99sendbot_boot
sudo ln -s /etc/init.d/sendbot_shutdown.sh /etc/rc0.d/K99sendbot_shutdown

这应该确保您的脚本在启动和关闭时执行。

PS:尝试更新 Ubuntu :-)

相关内容