Python脚本无法从systemd发出网络请求,可以从命令行运行

Python脚本无法从systemd发出网络请求,可以从命令行运行

我有一个用 Python 编写的简单服务器,它侦听 HTTP 请求,并且根据详细信息,可能会发出自己的 HTTP 请求,作为处理收到的请求的一部分。我的服务器发出的请求是几层抽象,但最终是使用常规的旧requests库发出的。

从命令行运行服务器时,效果很好。我现在尝试为其创建一个 systemd 服务,但它不再能够创建 HTTP 请求。所有其他功能似乎都正常工作,但请求失败,抛出一个丑陋的大错误。

我已包含我的 .service 文件和失败的 HTTP 请求的日志。主机名和脚本路径显然已被修改,但所有相关内容均保持不变。我认为代码的任何细节都不应该相关,因为这只是一个正常的requests请求,但如果需要,我可以提供更多详细信息。任何有关这些请求失败原因的见解将不胜感激。

框架服务器.服务:

[Unit]
Description=Run server for testing framework

[Service]
WorkingDirectory=/path/to/my/script
Environment=PYTHONUNBUFFERED=1
User=username
Group=username
Restart=on-failure
RestartSec=5
ExecStart=/usr/bin/env python3 server.py
SyslogIdentifier=server.py

[Install]
WantedBy=multi-user.target

尝试发送 GET 请求时出现错误日志my.request.url/index.php?/api/v2/get_case/4887104

Exception happened during processing of request from ('10.40.200.106', 56051)
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/urllib3/connection.py", line 144, in _new_conn
    (self.host, self.port), self.timeout, **extra_kw)
  File "/usr/lib/python3/dist-packages/urllib3/util/connection.py", line 60, in create_connection
    for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):
  File "/usr/lib/python3.6/socket.py", line 745, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno -2] Name or service not known
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 601, in urlopen
    chunked=chunked)
  File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 346, in _make_request
    self._validate_conn(conn)
  File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 852, in _validate_conn
    conn.connect()
  File "/usr/lib/python3/dist-packages/urllib3/connection.py", line 298, in connect
    conn = self._new_conn()
  File "/usr/lib/python3/dist-packages/urllib3/connection.py", line 153, in _new_conn
    self, "Failed to establish a new connection: %s" % e)
urllib3.exceptions.NewConnectionError: <urllib3.connection.VerifiedHTTPSConnection object at 0x7fb3bcd36208>: Failed to establish a new connection: [Errno -2] Name or service not known
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/requests/adapters.py", line 440, in send
    timeout=timeout
  File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 639, in urlopen
    _stacktrace=sys.exc_info()[2])
  File "/usr/lib/python3/dist-packages/urllib3/util/retry.py", line 398, in increment
    raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='my.request.url', port=443): Max retries exceeded with url: /index.php?/api/v2/get_case/4887104 (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7fb3bcd36208>: Failed to establish a new connection: [Errno -2] Name or service not known',))
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "/usr/lib/python3.6/socketserver.py", line 320, in _handle_request_noblock
    self.process_request(request, client_address)
  File "/usr/lib/python3.6/socketserver.py", line 351, in process_request
    self.finish_request(request, client_address)
  File "/usr/lib/python3.6/socketserver.py", line 364, in finish_request
    self.RequestHandlerClass(request, client_address, self)
  File "/usr/lib/python3.6/socketserver.py", line 724, in __init__
    self.handle()
  File "/usr/lib/python3.6/http/server.py", line 418, in handle
    self.handle_one_request()
  File "/usr/lib/python3.6/http/server.py", line 406, in handle_one_request
    method()
  File "server.py", line 194, in do_POST
    test_handler.run_tests(run_id, project_id, suite_id, case_id, test_ids)
  File "/path/to/my/script/lib/testing_automation/testrail_integration/test_handler.py", line 70, in run_tests
    my_case = client.get_case(case_id)
  File "/path/to/my/script/lib/testing_automation/testrail_integration/testrail_wrapper.py", line 68, in get_case
    return super().send_get(f'get_case/{case_id}')
  File "/path/to/my/script/lib/testing_automation/testrail_integration/testrail.py", line 41, in send_get
    return self.__send_request('GET', uri, filepath)
  File "/path/to/my/script/lib/testing_automation/testrail_integration/testrail_wrapper.py", line 48, in _APIClient__send_request
    return super()._APIClient__send_request(method, uri, data)
  File "/path/to/my/script/lib/testing_automation/testrail_integration/testrail.py", line 79, in __send_request
    response = requests.get(url, headers=headers)
  File "/usr/lib/python3/dist-packages/requests/api.py", line 72, in get
    return request('get', url, params=params, **kwargs)
  File "/usr/lib/python3/dist-packages/requests/api.py", line 58, in request
    return session.request(method=method, url=url, **kwargs)
  File "/usr/lib/python3/dist-packages/requests/sessions.py", line 520, in request
    resp = self.send(prep, **send_kwargs)
  File "/usr/lib/python3/dist-packages/requests/sessions.py", line 630, in send
    r = adapter.send(request, **kwargs)
  File "/usr/lib/python3/dist-packages/requests/adapters.py", line 508, in send
    raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='my.request.url', port=443): Max retries exceeded with url: /index.php?/api/v2/get_case/4887104 (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7fb3bcd36208>: Failed to establish a new connection: [Errno -2] Name or service not known',))

答案1

Jeff Schaller 在评论中确定了问题所在。我在 CLI 环境中配置了一个代理,这是发出请求所必需的,很久以前就设置好了,以至于我忘记了我需要它。

Environment=https_proxy="http://location.of.proxy"我通过包含在 .service 文件中解决了该问题。

相关内容