Python 获取旗舰VPN服务器地址

原先想让Deepin 2014.2和Windows 8.1一样自动添加VPN连接, 写了个Bash Shell, 中途因为解析HTML太麻烦不得不重拾多年不用的Python, 最后由于Deepin的nmcli和VPN服务功能上的问题, 还是实现不了自动添加VPN连接, 只能写出这样只获取服务器地址的半成品.

(坑爹的)源代码

#!/usr/bin/env python

import requests, re, time, uuid, os  
from pyquery import PyQuery as pq

username = 'username'  
password = 'password'

website = 'http://www.qjvpn.com.cn'

form = {  
    'username': username,
    'password': password,
    'from': '',
}

noUA = {  
    'User-Agent': ''
}

s = requests.Session()

res = s.post(  
    '%s/user/checklogin.php' % website,
    headers = noUA, data = form
)

#s.get(re.search(r'src="(\S+)"', res.text).group(1), headers = noUA)
q = pq(s.get('%s/user/serverlist.php' % website, headers = noUA).text)  
trs = q('table.sl_selected tr')

server = {}

for tr in trs:  
    tr = q(tr)
    ths = []
    for th in tr.children():
        th = q(th)
        ths.append(th.text().strip())
    server['QJ-'+ths[0]] = ths[1]

def generateConnection(name, gateway, username = username, password = password):  
    return u"""[connection]
id=%s  
uuid=%s  
type=vpn  
autoconnect=false  
timestamp=%s

[vpn]
service-type=org.freedesktop.NetworkManager.pptp  
gateway=%s  
require-mppe=yes  
user=%s  
refuse-chap=yes  
refuse-eap=yes  
refuse-pap=yes  
password-flags=0

[vpn-secrets]
password=%s

[ipv4]
method=auto""" % (name, uuid.uuid1(), int(time.time()), gateway, username, password)

for name, gateway in server.items():  
    print(name, gateway)
    #filename = '/etc/NetworkManager/system-connections/%s' % name
    #f = open(filename, 'w')
    #f.write(generateConnection(name, gateway).encode('utf8'))
    #f.close()
    #os.chmod(filename, 0600)