Ejemplo n.º 1
0
 def testGetDescriptionForFixedLineNumber(self):
     self.assertEqual("", name_for_number(AO_FIXED1, _ENGLISH))
     self.assertEqual("", name_for_number(UK_FIXED1, _ENGLISH))
     # If the carrier information is present in the files and the method
     # that assumes a valid number is used, a carrier is returned.
     self.assertEqual("Angolan fixed line carrier", name_for_valid_number(AO_FIXED2, _ENGLISH))
     self.assertEqual("", name_for_valid_number(UK_FIXED2, _ENGLISH))
Ejemplo n.º 2
0
def validate_phone_number(phone_number: str = ''):
    try:
        if not phone_number:
            return 'Missing phone number', -4
        if type(phone_number) != str:
            return "Unable to determine phone number", -4
        region = "KE"
        # Create a `PhoneNumber` object from a string representing a phone number
        # Specify country of origin of phone number.
        # This maybe unnecessary for numbers starting with '+' since they are globally unique.
        parsed_phone = phonenumbers.parse(phone_number, region)
        # Check whether it's a possible number (e.g. it has the right number of digits)
        if not phonenumbers.is_possible_number(parsed_phone):
            return "Possibly not a number. Check if e.g. number of digits is correct", -4
        # Check whether it's a valid number (e.g. it's in an assigned exchange)
        if not phonenumbers.is_valid_number_for_region(parsed_phone, region):
            return "Invalid phone number", -4
        # Format number as per international format code E164
        phone_number = phonenumbers.format_number(
            parsed_phone, phonenumbers.PhoneNumberFormat.E164)
        # Get the carrier of the phone number
        operator = carrier.name_for_number(parsed_phone,
                                           "en") if carrier.name_for_number(
                                               parsed_phone, "en") else ''
        return f"""Phone number valid. Phone: {phone_number}. Operator: {operator}""", 0
    except phonenumbers.phonenumberutil.NumberParseException as err:
        return f'{err}', -4
    except BaseException as ex:
        return f'{ex}', -4
Ejemplo n.º 3
0
    def validate(self):
        # check if all required fields are filled
        rv = FlaskForm.validate(self)
        if not rv:
            return False

        password = self.password.data
        if len(password) < 8 or len(password) > 100:
            self.password.errors.append(
                "Please enter a password of between 8 and 100 characters")
            return False

        telephone = self.telephone.data
        if not telephone:
            self.telephone.errors.append("Missing phone numbers")
            return False
        if type(telephone) != str:
            self.telephone.errors.append("Unable to determine phone number")
            return False
        region = "KE"
        # Create a `PhoneNumber` object from a string representing a phone number
        # Specify country of origin of phone number.
        # This maybe unnecessary for numbers starting with '+' since they are globally unique.
        phone = phonenumbers.parse(telephone, region)
        # Check whether it's a possible number (e.g. it has the right number of digits)
        if not phonenumbers.is_possible_number(phone):
            self.telephone.errors.append(
                "Possibly not a number. Check if e.g. number of digits is correct"
            )
            return False
        # Check whether it's a valid number (e.g. it's in an assigned exchange)
        if not phonenumbers.is_valid_number_for_region(phone, region):
            self.telephone.errors.append("Invalid phone number")
            return False
        # Format number as per international format code E164
        phone_number = phonenumbers.format_number(
            phone, phonenumbers.PhoneNumberFormat.E164)
        # Get the carrier of the phone number
        operator = carrier.name_for_number(
            phone, "en") if carrier.name_for_number(phone, "en") else ''
        print(phone_number, operator)
        # Ensure phone is Safaricom
        if operator != "Safaricom":
            self.telephone.errors.append(
                "Kindly use a Safaricom line for MPESA prompt")
            return False
        # If telephone is not registered, raise error
        user = User.query.filter_by(telephone=phone_number).first()
        if not user:
            self.telephone.errors.append('User not registered')
            return False

        # confirm user's password
        if not user.verify_password(password):
            self.password.errors.append("Invalid password")
            return False

        return True
Ejemplo n.º 4
0
def validate_phone_number(number):
    obj = phonenumbers.parse(number, "UG")
    if not phonenumbers.is_valid_number(obj):
        raise ValidationError("Invalid Phone number {0}".format(number))
    if (carrier.name_for_number(obj, "en") !=
            "MTN") or (carrier.name_for_number(obj, "en") != "Airtel"):
        raise ValidationError(
            "{0}: Only MTN | Airtel is supported at the moment".format(number))
    return "256{0}".format(obj.national_number)
Ejemplo n.º 5
0
 def testGetDescriptionForMobilePortableRegion(self):
     self.assertEqual("British carrier",
                      name_for_number(UK_MOBILE1, _ENGLISH))
     self.assertEqual(u"Brittisk operat\u00F6r",
                      name_for_number(UK_MOBILE1, "sv", region="SE"))
     self.assertEqual("British carrier",
                      name_for_number(UK_MOBILE1, _FRENCH))
     # Returns an empty string because the UK implements mobile number portability.
     self.assertEqual("", safe_display_name(UK_MOBILE1, _ENGLISH))
Ejemplo n.º 6
0
 def testGetDescriptionForNumberWithNoDataFile(self):
     self.assertEqual(
         "", name_for_number(NUMBER_WITH_INVALID_COUNTRY_CODE, _ENGLISH))
     self.assertEqual("", name_for_number(INTERNATIONAL_TOLL_FREE,
                                          _ENGLISH))
     self.assertEqual(
         "",
         name_for_valid_number(NUMBER_WITH_INVALID_COUNTRY_CODE, _ENGLISH))
     self.assertEqual(
         "", name_for_valid_number(INTERNATIONAL_TOLL_FREE, _ENGLISH))
Ejemplo n.º 7
0
def numberScan():
    global phoneNumberGET, phoneNumber, numberNSCAN, numberCC, numberC, numberLOCAL, numberINTER, countryNSCAN, locationNSCAN, carrierNameNSCAN
    phoneNumberGET = numberSCANentryVar.get()
    #GET INFORMATIONS - PHONE NUMBER SCANNER FRAME
    phoneNumber = phonenumbers.parse(phoneNumberGET, None)
    numberNSCAN = phonenumbers.format_number(
        phoneNumber, phonenumbers.PhoneNumberFormat.E164).replace('+', '')
    numberCC = phonenumbers.format_number(
        phoneNumber,
        phonenumbers.PhoneNumberFormat.INTERNATIONAL).split(' ')[0]
    numberC = phonenumbers.region_code_for_country_code(int(numberCC))
    numberLOCAL = phonenumbers.format_number(
        phoneNumber,
        phonenumbers.PhoneNumberFormat.E164).replace(numberCC, '')
    numberINTER = phonenumbers.format_number(
        phoneNumber, phonenumbers.PhoneNumberFormat.INTERNATIONAL)
    countryNSCAN = geocoder.country_name_for_number(phoneNumber, 'en')
    locationNSCAN = geocoder.description_for_number(phoneNumber, 'en')
    carrierNameNSCAN = carrier.name_for_number(phoneNumber, 'en')
    #APPLY RESULTS - PHONE NUMBER SCANNER FRAME
    numberReset()
    numberSCANentryVar.set(phoneNumberGET)
    localNSCANentryVar.set(numberLOCAL)
    interNSCANentryVar.set(numberINTER)
    countryNSCANentryVar.set("{} ({})".format(countryNSCAN, numberCC))
    areaNSCANentryVar.set(locationNSCAN)
    carrierNSCANentryVar.set(carrierNameNSCAN)
    for timezoneResult in timezone.time_zones_for_number(phoneNumber):
        timezoneNSCANentryVar.set(timezoneResult)
    if phonenumbers.is_possible_number(phoneNumber):
        validNSCANentryVar.set("VALID+POSSIBLE")
    else:
        validNSCANentryVar.set("INVALID")
Ejemplo n.º 8
0
def localScan(InputNumber, print_results=True):
    print("Running local scan...")

    FormattedPhoneNumber = "+" + formatNumber(InputNumber)

    try:
        PhoneNumberObject = phonenumbers.parse(FormattedPhoneNumber, None)
    except Exception as e:
        print(e)
    else:
        if not phonenumbers.is_valid_number(PhoneNumberObject):
            return False

        number = phonenumbers.format_number(
            PhoneNumberObject, phonenumbers.PhoneNumberFormat.E164
        ).replace("+", "")
        numberCountryCode = phonenumbers.format_number(
            PhoneNumberObject, phonenumbers.PhoneNumberFormat.INTERNATIONAL
        ).split(" ")[0]
        numberCountry = phonenumbers.region_code_for_country_code(
            int(numberCountryCode)
        )

        localNumber = phonenumbers.format_number(
            PhoneNumberObject, phonenumbers.PhoneNumberFormat.E164
        ).replace(numberCountryCode, "")
        internationalNumber = phonenumbers.format_number(
            PhoneNumberObject, phonenumbers.PhoneNumberFormat.INTERNATIONAL
        )

        country = geocoder.country_name_for_number(PhoneNumberObject, "en")
        location = geocoder.description_for_number(PhoneNumberObject, "en")
        carrierName = carrier.name_for_number(PhoneNumberObject, "en")

        if print_results:
            print("International format: {}".format(internationalNumber))
            print("Local format: {}".format(localNumber))
            print("Country found: {} ({})".format(country, numberCountryCode))
            print("City/Area: {}".format(location))
            print("Carrier: {}".format(carrierName))
            for timezoneResult in timezone.time_zones_for_number(PhoneNumberObject):
                print("Timezone: {}".format(timezoneResult))

            if phonenumbers.is_possible_number(PhoneNumberObject):
                print("The number is valid and possible.")
            else:
                print("The number is valid but might not be possible.")

    numberObj = {}
    numberObj["input"] = InputNumber
    numberObj["default"] = number
    numberObj["local"] = localNumber
    numberObj["international"] = internationalNumber
    numberObj["country"] = country
    numberObj["countryCode"] = numberCountryCode
    numberObj["countryIsoCode"] = numberCountry
    numberObj["location"] = location
    numberObj["carrier"] = carrierName

    return numberObj
Ejemplo n.º 9
0
 def get(self):
     res = dict()
     phoneNumber = self.request.get("number")
     country = str(self.request.get("country"))
     if phoneNumber != '' and country != '':
         try:
             info = phonenumbers.parse(phoneNumber, country.upper())
             res['country_code'] = '+' + str(info.country_code)
             res['carrier'] = carrier.name_for_number(info, "en")
             res['is_valid'] = phonenumbers.is_valid_number(info)
             res['is_possible'] = phonenumbers.is_possible_number(info)
             formats = dict()
             formats['national'] = phonenumbers.format_number(
                 info, phonenumbers.PhoneNumberFormat.NATIONAL)
             formats['international'] = phonenumbers.format_number(
                 info, phonenumbers.PhoneNumberFormat.INTERNATIONAL)
             formats['e164'] = phonenumbers.format_number(
                 info, phonenumbers.PhoneNumberFormat.E164)
             res['formats'] = formats
         except:
             res['message'] = 'error'
         self.response.headers.add_header("Access-Control-Allow-Origin",
                                          "*")
         self.response.headers['Content-Type'] = 'application/json'
         self.response.write(json.dumps(res))
     else:
         self.set_status(404)
Ejemplo n.º 10
0
def number_phone_function():
    print(" ")
    print("ATTENTION DONT FORGET => +48... <= OR SOMETHING LIKE THAT...")

    y = input("write phonenumber => ")
    x = phonenumbers.parse(y, None)
    print(x)

    x2 = phonenumbers.is_possible_number(x)
    print("is possible number? =>", x2)

    x3 = phonenumbers.is_valid_number(x)
    print("is valid number? =>", x3)

    #country..
    print("from where is use the number? =>",
          geocoder.description_for_number(x, 'pl'))

    #services..
    print("services of phonenumber? =>", carrier.name_for_number(x, 'pl'))

    #timezone..
    print("timezone =>", timezone.time_zones_for_number(x))

    print(" ")
Ejemplo n.º 11
0
    def get(self, number):
        code = 0
        message = 'success'
        data = {'number': number, 'isValid': None}

        try:
            if not number.startswith("+"):
                number = "+" + number
            logger.info('valid number:{0}'.format(number))
            x = phonenumbers.parse(number, None)
            data['countryCode'] = x.country_code
            data['nationalNumber'] = x.national_number
            # a = phonenumbers.is_possible_number(x)
            # 验证是否是可用的
            b = phonenumbers.is_valid_number(x)
            data['isValid'] = b
            # 本国格式化
            rx = phonenumbers.format_number(x, phonenumbers.PhoneNumberFormat.NATIONAL)
            data['nationalFormat'] = rx
            # 国际格式化
            rx = phonenumbers.format_number(x, phonenumbers.PhoneNumberFormat.INTERNATIONAL)
            data['internationalFormat'] = rx
            # 地区
            c = geocoder.description_for_number(x, "en")
            data['region'] = c
            # 运营商
            d = carrier.name_for_number(x, "en")
            data['carrier'] = d
            logger.info('valid result:{0}'.format(data))
        except Exception as err:
            logger.error(err, exc_info=True)
            code = 1000
            message = 'valid fail'
        return {'code': code, 'message': message, 'data': data}
Ejemplo n.º 12
0
def textmsg(phonenumber, msg, countrycode):
    number = phonenumbers.parse(phonenumber, countrycode)
    if carrier.name_for_number(number, 'en') != '':
        message = client.messages.create(body=msg, to=phonenumber, from_="+13177933648")
        pprint(message.sid)
        return True
    else: return False
Ejemplo n.º 13
0
def phone():
    os.system('figlet phone number')
    print(colored('================================', 'cyan'))
    # Parsing String to Phone number
    a = str(input(colored('enter number: ', 'green')))
    print(
        colored(
            '''=======================
[      TIME ZONE      ]
======================= ''', 'green'))
    phoneNumber = phonenumbers.parse(a)
    # Pass the parsed phone number in below function
    timeZone = timezone.time_zones_for_number(phoneNumber)
    time.sleep(1)

    # It print the timezone of a phonenumber
    print(colored(timeZone, 'yellow'))
    print(
        colored(
            '''=======================
[      NETWORK        ]
======================= ''', 'green'))
    ro_number = phonenumbers.parse(a, "RO")
    time.sleep(1)

    print(colored(carrier.name_for_number(ro_number, "en"), 'yellow'))
    print(
        colored(
            '''=======================
[      GEOLOCATION    ]
======================= ''', 'green'))
    ch_number = phonenumbers.parse(a, "CH")
    time.sleep(1)
    print(colored(geocoder.description_for_number(ch_number, "en"), 'yellow'))
Ejemplo n.º 14
0
    def onchange_mobile(self, cr, uid, ids, mobile, context=None):
        value = {}
        warning = {}

        if mobile:
            id_number = phonenumbers.parse(mobile, "ID")
            if not carrier._is_mobile(number_type(id_number)):
                warning = {
                    'title': ('Perhatian !'),
                    'message':
                    (('Masukkan nomor handphone dengan benar, misal: 0817989800'
                      )),
                }
                value['mobile'] = ''
            else:
                formatted_mobile = phonenumbers.format_number(
                    id_number, phonenumbers.PhoneNumberFormat.E164)
                provider_mobile = eval(
                    repr(carrier.name_for_number(id_number, "en")))
                value['mobile'] = formatted_mobile
                value['mobile_provider'] = provider_mobile

        return {
            'warning': warning,
            'value': value,
        }
Ejemplo n.º 15
0
def number_check(Phone_number):
    number = phonenumbers.parse(Phone_number)
    description = geocoder.description_for_number(number, "en")
    supplier = carrier.name_for_number(number, "en")
    info = [["country", "supplier"], [description, supplier]]

    return tabulate(info, headers="firstrow", tablefmt="github")
Ejemplo n.º 16
0
 def simple_scan(self, working=True):
     # function to get the basic info about a number (phonenumbers module)
     phone = phonenumbers.parse(self.phonenumber)
     if not phonenumbers.is_valid_number(phone):
         return False
     if phonenumbers.is_possible_number(phone):
         print(f"{b}{plus} The number is valid and possible.")
     else:
         print(f"{b}{warn} The number is valid but not possible.")
     international = phonenumbers.format_number(
         phone, phonenumbers.PhoneNumberFormat.INTERNATIONAL)
     countrycode = phonenumbers.format_number(
         phone, phonenumbers.PhoneNumberFormat.INTERNATIONAL).split(" ")[0]
     country = geocoder.country_name_for_number(phone, 'en')
     location = geocoder.description_for_number(phone, 'en')
     carrierr = carrier.name_for_number(phone, 'en')
     # ------------------------------------------------------------------------
     if working:
         print(f'{b}{plus} International Format : {international}')
         print(
             f'{b}{plus} Country name         : {country} ({countrycode})')
         print(f'{b}{plus} City/Province        : {location}')
         print(f'{b}{plus} Carrier              : {carrierr}')
         for time in timezone.time_zones_for_number(phone):
             print(f'{b}{plus} Timezone             : {time}')
Ejemplo n.º 17
0
def number_scan(phone):
    number = phonenumbers.parse(phone)
    des = geocoder.descriptiong_for_number(number, 'en')
    sup = carrier.name_for_number(number, 'en')
    info = [['Country', 'Supplier']], [des, sup]
    data = str(tabulate(info, headers='firstrow', tablefmt='github'))
    return data
Ejemplo n.º 18
0
def formatNumber(number):
    '''
    number 必须是带区号的
    '''

    code = 0
    message = 'success'
    data = {'number': number, 'isValid': None}

    print "number:", number
    x = phonenumbers.parse(number, None)
    print x
    data['countryCode'] = x.country_code
    data['nationalNumber'] = x.national_number
    # a = phonenumbers.is_possible_number(x)
    # 验证是否是可用的
    b = phonenumbers.is_valid_number(x)
    print b
    data['isValid'] = b
    # 格式化
    rx = phonenumbers.format_number(
        x, phonenumbers.PhoneNumberFormat.INTERNATIONAL)
    print rx
    data['format'] = rx
    # 地区
    c = geocoder.description_for_number(x, "en")
    print c
    data['region'] = c
    #运营商
    d = carrier.name_for_number(x, "en")
    print(d)
    data['carrier'] = d

    print data
Ejemplo n.º 19
0
def number_scanner(phone_number):
    number = phonenumbers.parse(phone_number)
    description = geocoder.description_for_number(number, "en")
    supplier = carrier.name_for_number(number, "en")
    info = [["Country", "Supplier"], [description, supplier]]
    data = str(tabulate(info, headers="firstrow", tablefmt="github"))
    return data
Ejemplo n.º 20
0
def numberScanner(number):
    number = phonenumbers.parse(number)
    description = geocoder.description_for_number(number, 'en')
    supplier = carrier.name_for_number(number, 'en')
    info = [['Country', 'Supplier'], [description, supplier]]
    data = str(tabulate(info, headers="firstrow", tablefmt="github"))
    return data
Ejemplo n.º 21
0
def scan(InputNumber, print_results=True):
    test('Running local scan...')

    FormattedPhoneNumber = "+" + formatNumber(InputNumber)

    try:
        PhoneNumberObject = phonenumbers.parse(FormattedPhoneNumber, None)
    except Exception as e:
        throw(e)
    else:
        if not phonenumbers.is_valid_number(PhoneNumberObject):
            return False

        number = phonenumbers.format_number(
            PhoneNumberObject,
            phonenumbers.PhoneNumberFormat.E164).replace('+', '')
        numberCountryCode = phonenumbers.format_number(
            PhoneNumberObject,
            phonenumbers.PhoneNumberFormat.INTERNATIONAL).split(' ')[0]
        numberCountry = phonenumbers.region_code_for_country_code(
            int(numberCountryCode))

        localNumber = phonenumbers.format_number(
            PhoneNumberObject, phonenumbers.PhoneNumberFormat.E164).replace(
                numberCountryCode, '')
        internationalNumber = phonenumbers.format_number(
            PhoneNumberObject, phonenumbers.PhoneNumberFormat.INTERNATIONAL)

        country = geocoder.country_name_for_number(PhoneNumberObject, "en")
        location = geocoder.description_for_number(PhoneNumberObject, "en")
        carrierName = carrier.name_for_number(PhoneNumberObject, 'en')

        if print_results:
            plus('International format: {}'.format(internationalNumber))
            plus('Local format: {}'.format(localNumber))
            plus('Country found: {} ({})'.format(country, numberCountryCode))
            plus('City/Area: {}'.format(location))
            plus('Carrier: {}'.format(carrierName))
            for timezoneResult in timezone.time_zones_for_number(
                    PhoneNumberObject):
                plus('Timezone: {}'.format(timezoneResult))

            if phonenumbers.is_possible_number(PhoneNumberObject):
                plus('The number is valid and possible!')
            else:
                warn('The number is valid but might not be possible.')

    numberObj = {}
    numberObj['input'] = InputNumber
    numberObj['default'] = number
    numberObj['local'] = localNumber
    numberObj['international'] = internationalNumber
    numberObj['country'] = country
    numberObj['countryCode'] = numberCountryCode
    numberObj['countryIsoCode'] = numberCountry
    numberObj['location'] = location
    numberObj['carrier'] = carrierName

    return numberObj
Ejemplo n.º 22
0
    def handleEvent(self, event):
        eventName = event.eventType
        srcModuleName = event.module
        eventData = event.data
        sourceData = self.sf.hashstring(eventData)

        if sourceData in self.results:
            return None
        else:
            self.results[sourceData] = True

        self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)

        if eventName in ['TARGET_WEB_CONTENT', 'DOMAIN_WHOIS', 'NETBLOCK_WHOIS']:
            # Make potential phone numbers more friendly to parse
            content = eventData.replace('.', '-')

            for match in phonenumbers.PhoneNumberMatcher(content, region=None):
                n = phonenumbers.format_number(match.number,
                                           phonenumbers.PhoneNumberFormat.E164)
                evt = SpiderFootEvent("PHONE_NUMBER", n, self.__name__, event)
                if event.moduleDataSource:
                    evt.moduleDataSource = event.moduleDataSource
                else:
                    evt.moduleDataSource = "Unknown"
                self.notifyListeners(evt)

        if eventName == 'PHONE_NUMBER':
            try:
                number = phonenumbers.parse(eventData)
            except BaseException as e:
                self.sf.debug('Error parsing phone number: ' + str(e))
                return None

            try:
                number_carrier = carrier.name_for_number(number, 'en')
            except BaseException as e:
                self.sf.debug('Error retrieving phone number carrier: ' + str(e))
                return None

            if number_carrier:
                evt = SpiderFootEvent("PROVIDER_TELCO", number_carrier, self.__name__, event)
                self.notifyListeners(evt)
            else:
                self.sf.debug("No carrier information found for " + eventData)

            #try:
            #    location = geocoder.description_for_number(number, 'en')
            #except BaseException as e:
            #    self.sf.debug('Error retrieving phone number location: ' + str(e))
            #    return None

            #if location:
            #    evt = SpiderFootEvent("GEOINFO", location, self.__name__, event)
            #    self.notifyListeners(evt)
            #else:
            #    self.sf.debug("No location information found for " + eventData)

        return None
Ejemplo n.º 23
0
Archivo: IPI.py Proyecto: wind2312/IPI
def PhoneNumber():
    numInput = input("Enter Phone Number - (Ex. = +447777123456) > ")
    ro_number = phonenumbers.parse(numInput, "RO")
    gb_number = phonenumbers.parse(numInput, "GB")
    timezone_gb = timezone.time_zones_for_number(gb_number)
    x = carrier.name_for_number(ro_number, "en")
    print("Carrier: " + (x))
    print("Timezone: " + str((timezone_gb)))
Ejemplo n.º 24
0
 def get_mobile_number_carrier(self):
     """
     get numbers mobile carrier, return empty string is not found.
     :return: string
     """
     from phonenumbers import carrier, parse
     number = parse(str(self.number))
     return carrier.name_for_number(number, "en")
Ejemplo n.º 25
0
        def num_scanner(phn_num):
            number = phonenumbers.parse(phn_num)
            description = geocoder.description_for_number(number, 'en')
            supplier = carrier.name_for_number(number, 'en')
            info = [["COUNTRY", "SUPPLIER"], [description, supplier]]

            data = str(tabulate(info, headers="firstrow", tablefmt="github"))
            return data
Ejemplo n.º 26
0
def localScan(InputNumber):
    global number
    global localNumber
    global internationalNumber
    global numberCountryCode
    global numberCountry

    print(code_info + 'Running local scan...')

    FormattedPhoneNumber = "+" + formatNumber(InputNumber)

    try:
        PhoneNumberObject = phonenumbers.parse(FormattedPhoneNumber, None)
    except:
        return False
    else:
        if not phonenumbers.is_valid_number(PhoneNumberObject):
            return False

        number = phonenumbers.format_number(
            PhoneNumberObject,
            phonenumbers.PhoneNumberFormat.E164).replace('+', '')
        numberCountryCode = phonenumbers.format_number(
            PhoneNumberObject,
            phonenumbers.PhoneNumberFormat.INTERNATIONAL).split(' ')[0]

        countryRequest = json.loads(
            requests.request(
                'GET',
                'https://restcountries.eu/rest/v2/callingcode/{}'.format(
                    numberCountryCode.replace('+', ''))).content)
        numberCountry = countryRequest[0]['alpha2Code']

        localNumber = phonenumbers.format_number(
            PhoneNumberObject, phonenumbers.PhoneNumberFormat.E164).replace(
                numberCountryCode, '')
        internationalNumber = phonenumbers.format_number(
            PhoneNumberObject, phonenumbers.PhoneNumberFormat.INTERNATIONAL)

        print(code_result +
              'International format: {}'.format(internationalNumber))
        print(code_result + 'Local format: 0{}'.format(localNumber))
        print(code_result + 'Country code: {}'.format(numberCountryCode))
        print(code_result + 'Location: {}'.format(
            geocoder.description_for_number(PhoneNumberObject, "en")))
        print(code_result + 'Carrier: {}'.format(
            carrier.name_for_number(PhoneNumberObject, 'en')))
        print(code_result + 'Area: {}'.format(
            geocoder.description_for_number(PhoneNumberObject, 'en')))
        for timezoneResult in timezone.time_zones_for_number(
                PhoneNumberObject):
            print(code_result + 'Timezone: {}'.format(timezoneResult))

        if phonenumbers.is_possible_number(PhoneNumberObject):
            print(code_info + 'The number is valid and possible.')
        else:
            print(code_warning +
                  'The number is valid but might not be possible.')
Ejemplo n.º 27
0
def details():
    ph_no = input("Enter the number")
    ch_no = phonenumbers.parse(ph_no,"CH")
    geo = geocoder.description_for_number(ch_no, "en")
    car = carrier.name_for_number(ch_no, "en")
    time = timezone.time_zones_for_number(ch_no)
    print(f'country : {geo}')
    print(f'carrier : {car}')
    print(f'timezone : {time}')
Ejemplo n.º 28
0
def IP():
    target = input('Enter the host to be scanned: ')
    phonne_number = phonenumbers.parse(target)

    print(target)
    print(geocoder.description_for_number(phonne_number, 'en'))
    print(carrier.name_for_number(phonne_number, 'en'))
    time.sleep(2)
    main()
Ejemplo n.º 29
0
def get_tel_provider():
    try:
        service_provider = phonenumbers.parse(myNumber, 'RO')
        if service_provider:
            print("Your service provider is " +
                  carrier.name_for_number(service_provider, 'en'))
        else:
            print('Service provider not avaliable')
    except:
        print("Service provider not found!!")
Ejemplo n.º 30
0
def ph_num_lookup():
    your_ph_num = input('Your Number: ')
    phone_number = phonenumbers.parse(your_ph_num)
    # put your phonenumber with the country code eg:+1xxxxxxxx
    print(geocoder.description_for_number(phone_number, 'en'))

    from phonenumbers import carrier
    service_provider = phonenumbers.parse(your_ph_num)
    # put your phonenumber with the country code eg:+1xxxxxxxx
    print(carrier.name_for_number(service_provider, 'en'))
Ejemplo n.º 31
0
def run(node):
    """ This returns any US phone numbers in the text.

        :param node:    a python dictionary with the 'text' field
    """
    results = []
    for match in phonenumbers.PhoneNumberMatcher(node['text'], "US"):
        results.append({
            "number"    : phonenumbers.format_number(match.number, phonenumbers.PhoneNumberFormat.E164),
            "location"  : geocoder.description_for_number(match.number, "en"),
            "carrier"   : carrier.name_for_number(match.number, "en"),
            "time_zone" : timezone.time_zones_for_number(match.number)
        })
    # http://stackoverflow.com/questions/11092511/python-list-of-unique-dictionaries
    return {"phonenumbers": uniq_lod(results, 'number')}
Ejemplo n.º 32
0
 def get_de_operator(self):
     self.phonenumber_details['operator'] = carrier.name_for_number(self.phonenumber_object, "de")
     return self.phonenumber_details['operator']
 def testGetDescriptionForNumberWithMissingPrefix(self):
     self.assertEqual("", name_for_number(UK_MOBILE2, _ENGLISH))
     self.assertEqual("", name_for_number(AO_MOBILE2, _ENGLISH))
 def testGetDescriptionForNumberWithNoDataFile(self):
     self.assertEqual("", name_for_number(NUMBER_WITH_INVALID_COUNTRY_CODE, _ENGLISH))
     self.assertEqual("", name_for_number(INTERNATIONAL_TOLL_FREE, _ENGLISH))
     self.assertEqual("", name_for_valid_number(NUMBER_WITH_INVALID_COUNTRY_CODE, _ENGLISH))
     self.assertEqual("", name_for_valid_number(INTERNATIONAL_TOLL_FREE, _ENGLISH))
Ejemplo n.º 35
0
def find_phone_numbers(source_txt):
    # logger = get_logger()
    tagged_phone_entities = []

    for match in re.finditer(phonenum_candidate_regex_str, source_txt, re.MULTILINE):
        # Extract the full-text value and the "normalized" value (i.e., digits only)
        value = source_txt[match.start() : match.end()]
        value_normalized = re.sub(u'[^\d]', u'', value)

        # Extract an excerpt of text that precedes the match
        excerpt_start = match.start() - EXCERPT_CHAR_BUFFER
        if excerpt_start < 0:
            excerpt_start = 0
        excerpt_prefix = source_txt[ excerpt_start : match.start() ]

        phone_number_obj = None

        try:
            # print "phone guess: %s"%value_normalized
            # Try using the 'phonenumbers' module to parse the number. Note that we need to prefix
            # the phone number string with "+" for parse() to work properly. If the number can't
            # be parsed it will throw a NumberParseException.
            phone_number_obj = phonenumbers.parse(u'+'+value_normalized, None)

            # More lenient than valid_num
            possible_num = phonenumbers.is_possible_number(phone_number_obj)
            valid_num= phonenumbers.is_valid_number(phone_number_obj)

            # print "possible=%s valid=%s"%(str(possible_num), str(valid_num))
            # If the phonenumbers module thinks the number is invalid BUT it is preceded by text
            # with a phone-related keyword, we'll accept the number. If the number is invalid and
            # doesn't have a phone-related keyword, however, skip it.
            if (not possible_num or not valid_num) and not contains_tel_keyword(excerpt_prefix[-15:]):
                continue

        except phonenumbers.phonenumberutil.NumberParseException as err:

            # The phonenumbers modules couldn't parse the number; however, if it's preceded by text
            # with a phone-related keyword we'll still accept it. Or put another way, if it is NOT
            # preceded by a phone keyword, skip it.
            if not contains_tel_keyword(excerpt_prefix[-15:]):
                continue

        #There seems to be a bug with some strings that cause partial numbers to be returned
        if len(value_normalized) < 7:
            continue

        # If we got this far, it means we're accepting the number as a phone number. Extract a snippet
        # of text that follows the match.
        excerpt_stop = match.end() + EXCERPT_CHAR_BUFFER
        if excerpt_stop > len(source_txt):
            excerpt_stop = len(source_txt)

        excerpt = source_txt[excerpt_start:excerpt_stop]
        excerpt_value_start = match.start() - excerpt_start
        excerpt_value_stop = excerpt_stop - match.end()

        # Remove carriage returns replace multiple, consecutive whitespace with a single space
        # so the excerpt will be compact and one line.
        excerpt = re.sub('\r+', u'', excerpt)
        excerpt = re.sub('\n+', u' ', excerpt)
        excerpt = re.sub(u'\s+', u' ', excerpt)

        print(u"Phone #: %s, \"%s\"" % (value_normalized, excerpt))

        entity_dict = {
            u"type": u"phone_number",
            u"value": value,
            u"value_normalized": value_normalized,
            u"note": None,
            u"body_offset_start": match.start(),
            u"body_offset_stop": match.end(),
            u"excerpt": excerpt,
            u"excerpt_value_start": excerpt_value_start,
            u"excerpt_value_stop": excerpt_value_stop,
            u"possible_area": None,
            u"possible_carrier": None
        }

        # If the phonenumbers module was able to construct an actual phone number object, attempt to
        # add some notes about the possible geographic region and telco carrier.
        if phone_number_obj is not None:
            area_name = geocoder.description_for_number(phone_number_obj, "en")
            if area_name:
                entity_dict[u'possible_area'] = u"Possible area: %s. " % area_name

            carrier_name = carrier.name_for_number(phone_number_obj, "en")
            if carrier_name:
                entity_dict[u'possible_carrier'] = u"Possible carrier: %s." % carrier_name

        tagged_phone_entities.append(entity_dict)

    return tagged_phone_entities
 def testGetDescriptionForInvalidNumber(self):
     self.assertEqual("", name_for_number(UK_INVALID_NUMBER, _ENGLISH))
     self.assertEqual("", name_for_number(AO_INVALID_NUMBER, _ENGLISH))
 def testGetDescriptionForMobilePortableRegion(self):
     self.assertEqual("British carrier", name_for_number(UK_MOBILE1, _ENGLISH))
     self.assertEqual(u("Brittisk operat\u00F6r"), name_for_number(UK_MOBILE1, "sv", region="SE"))
     self.assertEqual("British carrier", name_for_number(UK_MOBILE1, _FRENCH))
     # Returns an empty string because the UK implements mobile number portability.
     self.assertEqual("", safe_display_name(UK_MOBILE1, _ENGLISH))
 def testGetDescriptionForNonMobilePortableRegion(self):
     self.assertEqual("Angolan carrier", name_for_number(AO_MOBILE1, _ENGLISH))
     self.assertEqual("Angolan carrier", safe_display_name(AO_MOBILE1, _ENGLISH))
Ejemplo n.º 39
0
phonenumbers.is_valid_number(z)

print dir(phonenumbers.PhoneNumberFormat)
print
print x.country_code
print x
print str(x)
p = z
resp = {
    "countryCode": p.country_code,
    "nationalNumber": p.national_number,
    "isPossible": phonenumbers.is_possible_number(p),
    "isValid": phonenumbers.is_valid_number(p),
    "e164": phonenumbers.format_number(p, phonenumbers.PhoneNumberFormat.E164),
    "international": phonenumbers.format_number(p, phonenumbers.PhoneNumberFormat.INTERNATIONAL),
    "national": phonenumbers.format_number(p, phonenumbers.PhoneNumberFormat.NATIONAL),
    "rfc3966": phonenumbers.format_number(p, phonenumbers.PhoneNumberFormat.RFC3966),
    "location": geocoder.description_for_number(p, "en"),
    "country": geocoder.country_name_for_number(p, "en"),
}

print json.dumps(resp, indent=2)
exit()
print y
print z

print repr(carrier.name_for_number(x, "en"))
print repr(carrier.name_for_number(y, "en"))
print repr(carrier.name_for_number(z, "en"))
 def testGetDescriptionForPagerNumber(self):
     self.assertEqual("British pager", name_for_number(UK_PAGER, _ENGLISH))
 def testGetDescriptionForFixedOrMobileNumber(self):
     self.assertEqual("US carrier", name_for_number(US_FIXED_OR_MOBILE, _ENGLISH))