Python通过证书调用基于SSL的Webservice

首先,普及一下各种类型的证书知识,以及格式之间的转换方法:http://liuleijsjx.iteye.com/blog/433853
然后就是调用代码了:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'tan9le'
 
import urllib2 as u2
from suds.client import Client
from suds.transport.http import HttpTransport, Reply, TransportError
import httplib
 
 
class HTTPSClientAuthHandler(u2.HTTPSHandler):
    def __init__(self, key, cert):
        u2.HTTPSHandler.__init__(self)
        self.key = key
        self.cert = cert
 
    def https_open(self, req):
        #Rather than pass in a reference to a connection class, we pass in
        # a reference to a function which, for all intents and purposes,
        # will behave as a constructor
        return self.do_open(self.getConnection, req)
 
    def getConnection(self, host, timeout=300):
        return httplib.HTTPSConnection(host, key_file=self.key, cert_file=self.cert)
 
 
class HTTPSClientCertTransport(HttpTransport):
    def __init__(self, key, cert, *args, **kwargs):
        HttpTransport.__init__(self, *args, **kwargs)
        self.key = key
        self.cert = cert
 
    def u2open(self, u2request):
        tm = self.options.timeout
        url = u2.build_opener(HTTPSClientAuthHandler(self.key, self.cert))
        if self.u2ver() < 2.6:
            socket.setdefaulttimeout(tm)
            return url.open(u2request)
        else:
            return url.open(u2request, timeout=tm)
 
# These lines enable debug logging; remove them once everything works.
def getClient(url, key, cert):
    import logging
    logging.basicConfig(level=logging.INFO)
    logging.getLogger('suds.client').setLevel(logging.DEBUG)
    logging.getLogger('suds.transport').setLevel(logging.DEBUG)
    c = Client(url,transport = HTTPSClientCertTransport(key, cert))
    return c
 
def websevicewithcer(url):
    #key文件是从pfx导出的,命令是:openssl pkcs12 -in xxx.pfx -nocerts -nodes -out private.key
    key = 'D:/Work/cer/private.key' #这里换成你调用端的私钥文件
    #cer是IE导出的,记得要用Base64编码格式的
    cert = 'D:/Work/cer/public.cer' #这里换成你要调用的网址的客户端证书文件
    client = getClient(url, key, cert)
    result = client.service
    return result
 
def 自定义方法(param):
    wsdl_url = 'https://ip:port/xxx/services/portname?wsdl'
    websev = websevicewithcer(wsdl_url)
    #调用方式websev.方法名(参数)
    ws = websev.方法名(param)
    return ws
 
if __name__ == '__main__':
    result = 自定义方法('参数')
    print result

领取51CTO下载豆的Python脚本

#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'tan9le'
import urllib2
import cookielib
import urllib
import random
import re
 
def freedown(username,passwd):
    header = [('User-Agent','Mozilla/5.0 (Windows NT 6.1; WOW64; rv:14.0) Gecko/20100101 Firefox/14.0.1'),('Referer','http://home.51cto.com/index.php?s=/Index/index/reback/http%253A%252F%252Fdown.51cto.com')]
    cj = cookielib.LWPCookieJar()
    cookie_suppot = urllib2.HTTPCookieProcessor(cj)
    opener = urllib2.build_opener(cookie_suppot,urllib2.HTTPHandler)
    opener.addheaders = header
    urllib2.install_opener(opener)
    postdata = {
        'email': username,
        'passwd': passwd,
        'reback':'http%3A%2F%2Fdown.51cto.com',
    }
    request = urllib2.Request("http://home.51cto.com/index.php?s=/Index/doLogin",urllib.urlencode(postdata))
    conn = opener.open(request)
    partner = re.compile(r'src="(.+?)"')
    match = partner.findall(conn.read())
    for item in match:
        #print item
        opener.open(item)
    url = 'http://down.51cto.com/download.php'
    data = {'do':'getfreecredits','t':random.random()}
    req = urllib2.Request(url,data)
    r = opener.open(req,urllib.urlencode(data))
    print r.read()
 
if __name__ == "__main__":
    freedown('用户名','密码')

获取当前的天气信息

第一步:
从这里获取所有的省份编码:http://www.weather.com.cn/data/city3jdata/china.html
第二步:
从这里获取该省份下所有的地市编码:http://www.weather.com.cn/data/city3jdata/provshi/【省份编码】.html
比如江苏省:http://www.weather.com.cn/data/city3jdata/provshi/10119.html
第三步:
从这里获取该市/地区的所有行政区划代码:http://www.weather.com.cn/data/city3jdata/station/【省份编码】【地市编码】.html
比如江苏省南京市:http://www.weather.com.cn/data/city3jdata/station/1011901.html
第四步:
从这里获取最终天气信息:http://m.weather.com.cn/data/【省份编码】【地市编码】【区域编码】.html
比如江苏省南京市市区:http://m.weather.com.cn/data/101190101.html
或者不想要纯数据的话,可以从这里获取页面信息:http://www.weather.com.cn/weather/【省份编码】【地市编码】【区域编码】.shtml
比如江苏省南京市市区:http://www.weather.com.cn/weather/101190101.shtml

附Python获取南京天气的代码:

#!/usr/bin/python
# -*- coding: utf-8 -*-
 
 
import urllib2
import json
 
# get weather html and parse to json
weatherHtml = urllib2.urlopen('http://m.weather.com.cn/data/101190101.html').read()
weatherJSON = json.JSONDecoder().decode(weatherHtml)
weatherInfo = weatherJSON['weatherinfo']
 
# print weather info
print '城市:\t', weatherInfo['city']
print '时间:\t', weatherInfo['date_y']
print '24小时天气:'
print '温度:\t', weatherInfo['temp1']
print '天气:\t', weatherInfo['weather1']
print '风速:\t', weatherInfo['wind1']
print '紫外线:\t', weatherInfo['index_uv']
print '穿衣指数:\t', weatherInfo['index_d']
print '48小时天气:'
print '温度:\t', weatherInfo['temp2']
print '天气:\t', weatherInfo['weather2']
print '风速:\t', weatherInfo['wind2']
print '紫外线:\t', weatherInfo['index48_uv']
print '穿衣指数:\t', weatherInfo['index48_d']
print '72小时天气:'
print '温度:\t', weatherInfo['temp3']
print '天气:\t', weatherInfo['weather3']
print '风速:\t', weatherInfo['wind3']

Mac OS X设置全局环境变量

执行命令:

sudo vi /etc/launchd.conf 

然后文件内的书写格式为:

setenv 变量名 变量值

举例:

setenv JAVA_HOME /Library/Java/JavaVirtualMachines/jdk1.7.0_51.jdk/Contents/Home

重启后生效,但是这个方法好像对GUI(*.app)程序不起作用,仅对CLI起作用
从网上还找到另外一个针对单个GUI程序的环境变量的修改方法,但是我没有验证是否正确,先给摘录过来备份:
还是以eclipse举例:

sudo vi eclipse.app/Contents/Info.plist

添加以下内容至根dict标签下:

    <key>LSEnvironment</key>  
    <dict>  
        <key>JAVA_TOOL_OPTIONS</key>  
        <string>-Dfile.encoding=UTF-8</string>  
        <key>LANG</key>  
        <string>zh_CN.UTF-8</string>  
           
    </dict>

整个文件看上去大概像这样:

<?xml version="1.0" encoding="UTF-8"?>  
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">  
<plist version="1.0">  
<dict>  
    <key>LSEnvironment</key>  
    <dict>  
        <key>JAVA_TOOL_OPTIONS</key>  
        <string>-Dfile.encoding=UTF-8</string>  
        <key>LANG</key>  
        <string>zh_CN.UTF-8</string>  
           
    </dict>

然后执行:

    /System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister -v -f /Applications/eclipse/eclipse.app

使其生效,或者/Applications/eclipse改名后再次运行

OS X 10.9.x Mavericks 去除登录窗口中的 其他… 用户

运行【终端】,输入以下命令并回车,输入管理员密码验证后,可去除其他用户选择。

    sudo defaults write /Library/Preferences/com.apple.loginwindow SHOWOTHERUSERS_MANAGED -bool FALSE

运行【终端】,输入以下命令并回车,输入管理员密码验证后,可添加其他用户选择。

    sudo defaults write /Library/Preferences/com.apple.loginwindow SHOWOTHERUSERS_MANAGED -bool TRUE