基本的远程登录通过python [英] basic remote login by python

查看:147
本文介绍了基本的远程登录通过python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是python的新人。我正在练习。
现在我试图通过python远程登录我的wordpress博客。
下面是代码示例:

I am new in python. I am practicing it. Now i am trying to login remotely into my wordpress blog by python. Here is the code sample :

import urllib, urllib2, cookielib, re

cookie = cookielib.CookieJar()
redirect_handler= urllib2.HTTPRedirectHandler()
opener = urllib2.build_opener(redirect_handler, urllib2.HTTPCookieProcessor(cookie))
url = 'http://example.com/abc/wp-login.php'
data = urllib.urlencode({"log":"user","pwd":"pass","rememberme":"forever","wp-submit":"Log In","redirect_to":
"http://example.com/abc/wp-admin","testcookie":1})

req = opener.open(url, data)
get_page = req.read()
get_url  = req.geturl()
print get_page

但是当我检查返回页面时,它没有正确登录(或者没有正确地重定向)。我可以很容易地在php与 curl 它有一个选项,以跟随位置。我认为这很可能是重定向问题。不是吗?那么哪个函数应该在这里使用?

But it's not login properly ( or it is not redirecting properly. ) when i check the return page . I can do it easily in php with curl which has a option to follow location. I think it's most probably the redirection problem. Isn't it ? So which function should use here ?

尊敬

更新

它的工作。它需要检查重定向的网址。所以我把这一行之前的代码,并验证登录成功。
req2 = opener.open('http://symsell.com/abc/wp-admin').read()

It's working. It's need to check the redirected url. So i put this line after previous code and verify that login is successful . req2 = opener.open('http://symsell.com/abc/wp-admin').read()

推荐答案

使用请求,您的代码将更简单。

Use requests and your code will be much simpler.

http://docs.python-requests.org修改的快速入门示例/ en / latest /

>>> import requests
>>> r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
>>> r.status_code
200
>>> r.headers['content-type']
'application/json; charset=utf8'
>>> r.encoding
'utf-8'
>>> r.text
u'{"type":"User"...'
>>> r.json()
{u'private_gists': 419, u'total_private_repos': 77, ...}

当然,你也可以添加对cookie的支持,但你要求基本授权,并显示。

Of course you might also add support for cookies there, but you asked for basic authorization and that is shown.

这篇关于基本的远程登录通过python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆