我目前正在编写一个python函数,以通过vpn自动从远程服务器收集一些csv数据,我在Session对象中提出了一系列请求以模仿手动登录过程,但是我遇到了问题会话保持登录状态。
尽管登录请求和随后的每个请求均返回200响应,但我没有收到存储在我的响应或会话中的Set-cookie请求标头设置的任何cookie-因此我的下载链接仅重定向至登录页面。
这是我的请求代码:
with requests.Session() as session:
adapter = HTTPAdapter(max_retries=10)
session.mount('http://', adapter)
login = session.get(
request_credentials["form login"]["url"],
auth=(username, password),
headers=request_credentials["form login"]["headers"],
timeout=10
)
start = session.get(
request_credentials["start"]["url"],
headers=request_credentials["start"]["headers"],
timeout=10
)
browse = session.get(
request_credentials["browse"]["url"],
headers=request_credentials["browse"]["headers"],
timeout=10
)
files = session.get(
request_credentials["files"]["url"],
headers=request_credentials["files"]["headers"],
timeout=10
)
下面是一个请求凭据页面的示例,这些页面是从chrome上成功完成的手动http请求中复制的。
form login:
url: "http://192.168.103.51/FormLogin"
headers:
{
'Connection': 'keep-alive',
'Cache-Control': 'max-age=0',
'Origin': 'http://192.168.103.51',
'Upgrade-Insecure-Requests': '1',
'Content-Type': 'application/x-www-form-urlencoded',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
'Referer': 'http://192.168.103.51/www/start.html',
'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'en-US,en;q=0.9',
}
这是通过chrome成功发送的手动HTTP请求的curl输出(已删除数据):
curl 'http://192.168.103.51/FormLogin' -H 'Connection: keep-alive' -H 'Cache-Control: max-age=0' -H 'Origin: http://192.168.103.51' -H 'Upgrade-Insecure-Requests: 1' -H 'Content-Type: application/x-www-form-urlencoded' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36' -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3' -H 'Referer: http://192.168.103.51/start.html' -H 'Accept-Encoding: gzip, deflate' -H 'Accept-Language: en-US,en;q=0.9' -H 'Cookie: siemens_ad_session=w6F/0wAAAQACAOPzwKhnCwAAAAAAAAAA8+M='
如果我从上一个会话中手动传递有效的cookie,我可以使代码按预期工作,但是我无法弄清楚为什么请求没有在Set-cookie标头中获取cookie。