Hébergeur de fichiers indépendant

pamir.py

À propos

Type de fichier
Fichier PY de 5 Ko (text/x-python)
Confidentialité
Fichier public, envoyé le 29 juin 2013 à 03:03, depuis l'adresse IP 82.227.x.x (France)
Sécurité
Ne contient aucun Virus ou Malware connus - Dernière vérification: 23 heures
Statistiques
La présente page de téléchargement a été vue 473 fois depuis l'envoi du fichier
Page de téléchargement

Aperçu du fichier


#!/usr/bin/env python
import datetime, getopt, os, signal, sys, time, urllib.request
from sys import *
from operator import itemgetter
from decimal import *

path_conf = "/etc/pacman-mirrors.conf"
onlyCountry=[]

def alarm_handler(signum, frame):
    raise TimeoutError("Ici")
def timeOut(timeout):
    signal.signal(signal.SIGALRM, alarm_handler)
    signal.alarm(timeout) # produce SIGALRM in `timeout` seconds


serverList = []
nbServer = 0
arch = os.uname().machine
#getcontext().prec = 3

try :
    fi = open(path_conf, "r")
except :
    print("Cannot open file", path_conf)
    exit(1)


# Analyze the file "pacman.conf"
# ==============================
while 1 :
    line = fi.readline()
    if line == "" :
        break
    line.strip()
    if line == "" :
        break
    if line[0] == '#' or line[0] == '\n' :
        continue
    i = line.find("=")
    if i == -1 :
        continue
    snom = line[0:i]
    i = i + 1
    j = len(line) -1
    if line[i] == '"' :
        i = i + 1
        if line[j -1] == '"' :
            j = j - 1
    sval = line[i:j]
    if snom == "Branch" :
        branch=sval
    elif snom == "MirrorlistsDir" :
        pathMirrors = sval + "/"
    elif snom == "OutputMirrorlist" :
        outputMirrorList = sval

try :
    os.chdir(pathMirrors)
except :
    print("Cannot change directory to", pathMirrors)
    exit(1)
listeDir = os.listdir(pathMirrors)
listeDir.sort()


#
# Read the arguments of the command line
# ======================================
def usage():
    print("\nUsage :", sys.argv[0], "[-b branch] [-c country[,country...] [-h]",
           "[-o output]")
try:
    opts, args = getopt.getopt(sys.argv[1:], 'b:c:ho:')
    for opt, arg in opts :
       if opt == "-b" :
           if arg in ("stable", "testing", "unstable") :
               branch = arg
           else :
               print("Error : unknown branch", arg)
               exit(1)
       elif opt == "-c" :		# Restrict mirrorlist to any countries
           l = len(arg)
           i = 0
           while i < l :
              j = arg[i:].find(',')
              if j == -1 :
                  s = arg[i:]
                  i = l
              else :
                  s = arg[i:i+j]
                  i = i + j + 1
              if os.path.exists("/etc/pacman.d/mirrors/" + s) == False :
                  print("No server in country", s)
                  exit(1)

              onlyCountry.append(s)
       elif opt == "-o" :
           outputMirrorList = arg
       else :
           usage()
           print("\n -b branch                     stable, testing, or unstable")
           print(" -c country[,country...]       use only mirrors from country(ies)")
           print("( ", end="") 
           for i in listeDir :
               print(i, end=" ")
           print(")")
           print(" -h                            show help")
           print(" -o output                     specify output file")
           print("")

           exit(0)
except getopt.GetoptError as err:
    print(err)
    usage()
    exit(1)

try :
    fo = open(outputMirrorList, "w")
except :
    print("Not enough rights to create", outputMirrorList)
    if os.getuid() != 0 :
        print("Error : must be root to do that.")
    exit(1)

# Main loop
# =========
listeSer=[]
for country in listeDir :
    if len(onlyCountry) != 0 and country not in onlyCountry :
        continue
    print(country)
    fi = open(country, "r")
    while 1 :
        s = fi.readline()
        if s == '' :
            break
        if s[0] != 'S' :
            continue
        urlServer = s[9:-1]
        urlServer = urlServer.replace("$branch", branch)
        print("......", urlServer, end='')
        sys.stdout.flush()
        j = urlServer.find(branch)
        url = urlServer[0:j] + "state"
        start = time.time()
        try :
            furl  = urllib.request.urlopen(url, timeout=2)
        except :
            print("\rError!")
            continue
        timeOut(2)
        try :
            resp =  furl.read()
            d = resp.find(b"date=")
            s = resp[d+5:].decode('utf-8')
            t = s.find("T")
            date = s[0:t]
            hour = s[t+1:-1]
            elapsed = round((time.time() - start), 3)
            selapsed = "{:6.4}".format(Decimal(elapsed).quantize(Decimal('.001')))
            print("\r", selapsed, sep="")
            # print("\r{:6.4}".format(Decimal(elapsed).quantize(Decimal('.001'))))
            sys.stdout.flush()
            serverList.append([country, selapsed, date + " " + hour, urlServer])
            nbServer = nbServer + 1
        except :
            print("\rError2!")
        finally :
            signal.alarm(0) # cancel alarm
            furl.close()
    fi.close()
#    break


#
# Build the file "mirrorlist"
# ===========================
serverList = sorted(serverList, key=itemgetter(1))
fo.write("##\n")
fo.write("## Manjaro Linux repository mirrorlist\n")
fo.write("## Generated on ")
fo.write(datetime.datetime.now().strftime("%d %b %Y"))
fo.write("\n##\n")
fo.write("## Use pacman-mirrors to modify\n")
fo.write("##\n\n")
i = 0
while (i < nbServer) :
    fo.write("\n## Location : ")
    fo.write(serverList[i][0])
    fo.write("\n## Time     :")
    fo.write(serverList[i][1])
    fo.write("\n## Updated  : ")
    fo.write(serverList[i][2])
    fo.write("\nServer = ")
    fo.write(serverList[i][3])
    fo.write("\n")
    i = i + 1


Partager le fichier


Télécharger pamir.py


Télécharger pamir.py