需要用到ping这个module(https://github.com/jedie/python-ping/),
其中ping.PING_SHOW_LOG是我自己加在ping内的, 可以用来屏蔽一些ping中的输出, 另外, ping内有一个地方会在出错后直接exit, 在我的版本内也去掉了. 但出于版权原因, 我就不发了. 用的话, 自己改吧…
用python用的很弱, 所以不要笑我, 以上.
手动补上了全部的行首空格…看啦要研究一下怎么能在wordpress中粘贴时保留空格了…
#!/usr/bin/env python # -*- encoding: utf-8 -*- import os, sys, string import socket import urllib import re def getv2exip(): import subprocess v2excmd = "nslookup a1.phobos.apple.com 178.79.131.110 | tail -n 2 | head -n 1 | sed 's/Address\: //g'" sp = subprocess.Popen(v2excmd, stdout = subprocess.PIPE, shell = True) v2exip = sp.stdout.read() return v2exip.replace("\n", "").replace("\r", "") def getjustpingip(): justpingips = [] try: justpingURL = "http://www.just-ping.com/index.php?vh=a1.phobos.apple.com&c=&s=ping%%21" print justpingURL justpingContent = urllib.urlopen(justpingURL).read() justping_re = re.compile('xmlreqGET\(\'(.*)\',\'.*') alljustpingurl = justping_re.findall(justpingContent) for url in alljustpingurl: fullurl = "http://www.just-ping.com/%s"%url print fullurl justpingreturn = urllib.urlopen(fullurl).read() if len(justpingreturn) > 0: parts = justpingreturn.split(":;") justpingip = parts.pop() if len(justpingip.split(".")) == 4: justpingips.append(justpingip) return justpingips except: print "getjustpingip has some error" return justpingips def getFastestIP(): allips = [] allips.append(getv2exip()) print "get v2exip finish" allips.extend(getjustpingip()) print "get justpingip finish" pingDelay = {} import ping ping.PING_SHOW_LOG = False for ip in allips: try: delay = ping.Ping(ip, timeout=2000).do() if not delay is None: #print "%s: %s" % (ip, delay) pingDelay[ip] = delay except socket.error, e: print "ping Error: ", e from operator import itemgetter sortedPingDelay = sorted(pingDelay.iteritems(), key=itemgetter(1)) if len(sortedPingDelay) > 1 : fastest = sortedPingDelay[0] return fastest[0] else: print "Can not find any ip addresses" exit(0) def changeHostsFile(ip): hostsLines = [] hosts = open('/etc/hosts') hosts.seek(0) for line in hosts.readlines(): if line.find("phobos.apple.com") == -1: hostsLines.append(line) hosts.close() hostsLines.append("\n") for i in range(2000): hostsLines.append("%s\t\ta%d.phobos.apple.com\n" % (ip, i+1)) hosts = open('/etc/hosts', "w") hosts.seek(0) hosts.writelines(hostsLines) hosts.close() def main(): ip = getFastestIP() print "fastest: %s" % ip changeHostsFile(ip) if __name__ == '__main__': main()
哈哈,不错,我都没有想到用PY写这么一个脚本,Py首行不用缩进一个吧
[回复]
透明de面具 回复:
8月 28th, 2012 at 00:25
首行?不用吧
[回复]