本文介绍了Python请求,如何为传出流量指定端口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在一个项目中,我们想要为防火墙上的传入流量分配白名单数据包筛选器,并且我们正在将Python脚本与请求库配合使用,以对该网络之外的某些服务器发出一些https请求.目前,脚本正在使用临时端口连接到服务器,但是我们希望通过特定端口发出这些https请求.这将使我们能够为这些端口创建严格的白名单.

I'm working on a project where we want to assign a whitelist packet filters for incoming traffic on a firewall and we are using python script with requests library to make some https requests to some servers outside of that network. For now the script is using ephemeral ports to connect to the servers, but we would like to make these https requests through specific ports. This would allow us to create strict whitelist for these ports.

我如何指定请求库通过其发送请求的端口?脚本当前正在使用以下类型的代码来发送必要的请求.

How can I specify the port to the requests library through which the request should be sent? Script is currently using the following type of code to send the necessary requests.

response = requests.post(data[0], data=query, headers=headers, timeout=10)

这可行,但是我现在需要指定通过其发送http post请求的端口,以允许在网络上进行更严格的数据包筛选.如何实现此端口声明?我已经从数个来源中寻找解决方案,但一无所获.

This works, but I would now need to specify the port through which the http post request should be sent to allow for more strict packet filtering on the network. How could this port declaration be achieved? I have searched for solution to this from several sources already and came up with absolutely nothing.

推荐答案

requests建立在 urllib3 ,它可以设置连接的源地址;将源地址设置为('', port_number)时,告诉它使用默认主机名,但选择一个特定端口.

requests is built on urllib3, which offers the ability to set a source address for connections; when you set the source address to ('', port_number) you tell it to use the default host name but pick a specific port.

您可以在池管理器,然后您通过创建新的requests使用其他池管理器noreferrer>运输适配器:

You can set these options on the pool manager, and you tell requests to use a different pool manager by creating a new transport adapter:

from requests.adapters import HTTPAdapter
from requests.packages.urllib3.poolmanager import PoolManager


class SourcePortAdapter(HTTPAdapter):
    """"Transport adapter" that allows us to set the source port."""
    def __init__(self, port, *args, **kwargs):
        self._source_port = port
        super(SourcePortAdapter, self).__init__(*args, **kwargs)

    def init_poolmanager(self, connections, maxsize, block=False):
        self.poolmanager = PoolManager(
            num_pools=connections, maxsize=maxsize,
            block=block, source_address=('', self._source_port))

在会话对象中使用此适配器,以下使用54321作为源端口为 all HTTP和HTTPS连接安装适配器:

Use this adapter in a session object, the following mounts the adapter for all HTTP and HTTPS connections, using 54321 as the source port:

s = requests.Session()
s.mount('http://', SourcePortAdapter(54321))
s.mount('https://', SourcePortAdapter(54321))

您只能设置一个源端口,一次只能将一个活动连接限制为一个.如果需要在端口之间轮换,请注册多个适配器(每个URL一个)或每次重新注册所有安装.

You can only set the one source port, limiting you to one active connection at a time. If you need to rotate between ports, register multiple adapters (one per URL) or re-register the catch-all mounts each time.

请参见 create_connection()实用程序功能文档有关source_address选项的详细信息:

See the create_connection() utility function documentation for the details on the source_address option:

这篇关于Python请求,如何为传出流量指定端口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 04:29