I'm new to python and am trying to re-write a php script I have in Python using the requests library. I'm having a hard time, though.
The script basically logs into a specific website using curl that requires a user/pass. PHP code below:
$username = 'user';
$password = 'pass';
$cookie_file_path = "cookie.txt";
$loginurl = "http://www.example.com/login";
$agent = "Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.7.12) Gecko/20050915 Firefox/1.0.7";
$ch = curl_init();
// extra headers
$headers[] = "Accept: */*";
$headers[] = "Connection: Keep-Alive";
// curl options
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path);
// set first URL
curl_setopt($ch, CURLOPT_URL, $loginurl);
// start session and get cookies
$content = curl_exec($ch);
//set params
$fields = array();
$fields['p'] = "";
$fields['dest'] = "";
$fields['username'] = $username;
$fields['password'] = $password;
$loginurl = "https://www.example.com/login";
// set postfields
$POSTFIELDS = http_build_query($fields);
// set to login url
curl_setopt($ch, CURLOPT_URL, $loginurl);
// set post options
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $POSTFIELDS);
// perform login
$result = curl_exec($ch);
And this is my python code:
import requests
class Login():
def Login():
username = "user"
password = "pass"
with requests.Session() as s:
cookiePath = "cookie.txt"
loginUrl = "http://www.example.com/login"
headers = {"Accept": "*/*", "Connection": "Keep-Alive"}
resp = s.get(loginUrl)
params = {"p": "", "dest": "", "username": username, "password": password}
loginUrl = "https://www.example.com/login"
resp = s.post(loginUrl, params)
if __name__ == '__main__':
Login()
I'm not entirely sure what is going wrong. While debugging I"m printing out the header and the status code and it looks ok. I read somewhere that the requests library handles cookies for you, so I'm assuming I don't have to do anything with them, but I'm not sure. However, I have a feeling that's where things are going wrong. Does anything stand out?
dictbut not using it. You also omitted the User Agent header from the python version. You can checkresp.historyto see if any redirects were issued. Other than that, you could check the logs on the login target app if you have access to them.if __name__ == '__main__': Login().Login()? The classLoginhas a methodLoginthat does the actual work.