跳转到主要内容

Python中的Namecheap API客户端(Bemmu/PyNamecheap的分支)

项目描述

Namecheap API for Python

PyPi Version License Button PyPI - Downloads PyPI - Python Version GitHub last commit

PyNamecheap是Python中的Namecheap API客户端。API本身的文档可以在https://www.namecheap.com/support/api/intro/找到

此客户端支持

  • 注册域名
  • 检查域名名称可用性
  • 列出您已注册的域名
  • 获取域名联系信息
  • 将DNS信息设置为默认值
  • 设置DNS主机记录

注意:这是一个Bemmu/PyNamecheap的分支.

原始库是由@Bemmu创建的 - 我们(@Privex)分支了库,以便我们能够进行各种重大更改,包括使用一些防止与Python 2.x及之前版本向后兼容的特性。

如果您绝对需要使用3.6.0之前的Python版本,那么您应该使用原始包:Bemmu/PyNamecheap

安装

首先,通过运行python3 -V来检查您的Python版本

user@host ~ $ python3 -V
Python 3.8.3

对于Python 3.7及更高版本

要安装我们的分支(Privex/PyNamecheap)的python包 - 使用pip3pipenv并安装包名privex-namecheap

# Using standard Pip
pip3 install -U privex-namecheap

# Using Pipenv
pipenv install privex-namecheap

对于Python 3.6.x

如果您正在运行Python 3.6.x,则需要使用py36额外功能安装我们的包 - 或者手动安装dataclasses包。

# Using standard Pip
pip3 install -U 'privex-namecheap[py36]'

# Using Pipenv
pipenv install 'privex-namecheap[py36]'

如果您正在运行Python 3.7或更高版本,请不要安装 privex-namecheap[py36]。这将破坏您内置的Python dataclasses模块。

对于Python 3.5.x或更早版本...

原始库是由@Bemmu创建的 - 我们(@Privex)分支了库,以便我们能够进行各种重大更改,包括使用一些防止与Python 2.x及之前版本向后兼容的特性。

这意味着无法使用小于 3.6.0 的任何Python版本来使用 privex-namecheap

如果您绝对需要使用3.6.0之前的Python版本,那么您应该使用原始包:Bemmu/PyNamecheap

如何注册开始使用API

API有两个环境,生产环境和沙盒环境。由于此API在注册域名时会花费真实货币,因此请先通过访问 http://www.sandbox.namecheap.com/ 并创建一个账户来开始使用沙盒环境。生产环境和沙盒环境中的账户是不同的,因此即使您已经有了Namecheap账户,您也需要一个新的账户。

拥有账户后,请前往“个人资料”。

Profile

从那里,再次选择“个人资料”菜单,然后选择“工具”。滚动到页面底部至“商业与开发工具”,并选择“管理”中的“Namecheap API访问”。

API menu

您将进入凭证页面。从这里,您需要记下您的API密钥、用户名,并将您的IP地址添加到允许访问账户的IP地址白名单中。您可以通过在Google上搜索“我的IP地址”来检查您的公共IP,并将其添加到此。它可能需要一些时间才能开始工作,因此如果API访问最初不起作用,请不要慌张。

Credentials

如何从Python访问API

将namecheap.py复制到您的项目中。在Python中,您可以通过以下方式访问API

from namecheap import Api
# api_username, api_key, client_ip_address
api = Api('NamecheapUsername', 'YourNamecheapAPIKey', '12.34.56.78', sandbox=True, debug=True)

# Using keyword arguments (recommended - more reliable in the event the constructor is changed)
api = Api(
    ApiUser='NamecheapUsername', 
    ApiKey='YourNamecheapAPIKey',
    ClientIP='12.34.56.78', 

    # OPTIONAL. You only need to specify UserName if you're managing resources on a different
    # Namecheap account from your own account - e.g. someone has granted your account permission
    # to manage their domains etc.
    UserName='NamecheapUsername', 

    # By default, sandbox and debug are both False. Set sandbox=True to use the Namecheap Sandbox API,
    # and set debug=True to enable verbose debug logging to help you understand what the library is
    # doing behind the scenes.
    sandbox=True, debug=True
)

字段是上面凭证屏幕中出现的字段。

用户名出现两次,因为您可能代表其他人操作。

使用API注册域名 + 常见用法示例

很遗憾,您需要一系列联系详细信息来注册域名,因此这不仅仅是提供域名名称那么简单。

在沙盒中,以下联系详细信息是可以接受的。最棘手的是电话号码,它必须按所示格式填写。

from namecheap import Api, DomainRecord

contact_details = dict(
    FirstName='Jack',
    LastName='Trotter',
    Address1='Ridiculously Big Mansion, Yellow Brick Road',
    City='Tokushima',
    StateProvince='Tokushima',
    PostalCode='771-0144',
    Country='Japan',
    Phone="+81.123123123",
    EmailAddress='jack.trotter@example.com'
)

api = Api('NamecheapUsername', 'YourNamecheapAPIKey', '12.34.56.78', sandbox=True, debug=True)

# First let's find out how much various TLDs cost at the moment
tld_prices = api.get_tld_prices('com', 'org', 'net', 'bz', 'xyz', 'us')
for tld, price in tld_prices.items():
    print(f".{tld} pricing - Current Price: ${price.total_your_price:.2f} | Regular Price: ${price.total_regular_price:.2f}")
print("-------------")
"""
(Example output)
.com pricing - Current Price: $9.06 | Regular Price: $9.06
.org pricing - Current Price: $13.16 | Regular Price: $13.16
.net pricing - Current Price: $12.16 | Regular Price: $13.16
.bz pricing - Current Price: $21.88 | Regular Price: $21.88
.xyz pricing - Current Price: $1.18 | Regular Price: $11.06
.us pricing - Current Price: $3.88 | Regular Price: $8.48
-------------
"""

# Next let's specifically get just the .com TLD price
com_price = api.get_tld_prices('com')
print(f"Price you'll pay: ${com_price.total_your_price:.2f} | Regular Non-promo Price: ${com_price.total_regular_price:.2f}")

# Now for the important part - registering the domain. We need to specify all of the contact details
# when registering the domain.
reg = api.domains_create(
    'mycooldomain.com',
    **contact_details
)
print("Domain registration result:", reg)
# domains_create is also available as the alias: register_domain

# Assuming no exception occurred, then we can now setup the records for the domain

# Using replace_records, we can get rid of all the default parking page records etc., and overwrite them
# with our custom records - in one fell swoop.
api.replace_records(
    'mycooldomain.com',
    DomainRecord('A', '185.130.44.10'),               # Name: @   | Type: A     | Value: 185.130.44.10
    DomainRecord('AAAA', '2a07:e00::abc'),            # Name: @   | Type: A     | Value: 185.130.44.10
    DomainRecord('CNAME', 'mycooldomain.com', 'www')  # Name: www | Type: CNAME | Value: mycooldomain.com
)

# Using add_record, we can insert singular records to the existing records, instead of overwriting them
api.add_record('mycooldomain.com', 'TXT', 'hello world')          # Name: @    | Type: TXT | Value: hello world
api.add_record('mycooldomain.com', 'A', '127.0.0.1', 'test')      # Name: test | Type: A   | Value: 127.0.0.1

# Using delete_record, we can delete individual records based on their type, content, and sub-domain
api.delete_record('mycooldomain.com', 'TXT', 'hello world')       # Delete the root domain TXT record 'hello world'
api.delete_record('mycooldomain.com', 'A', '127.0.0.1', 'test')   # Delete the 'test' subdomain A record '127.0.0.1'

info = api.domains_getInfo('mycooldomain.com')
print(info.expired_date)   # Output: 2020-11-05 00:00:00

# If mycooldomain.com is expiring in the next 60 days, renew it for one year.
if info.days_until_expires < 60:
    api.renew_domain('mycooldomain.com')

# Change the nameservers for mycooldomain.com to ns1.privex.io to ns3.privex.io
api.set_nameservers('mycooldomain.com', 'ns1.privex.io', 'ns2.privex.io', 'ns3.privex.io')

# Change the nameservers for mycooldomain.com back to the default Namecheap nameservers,
# to allow using the domain with Namecheap's email service, URL redirect records + other features.
api.domains_dns_setDefault('mycooldomain.com')

此调用应在沙盒中成功,但如果您在注册后使用API检查此域名的可用性,可用性不会改变。这是正常的。

如何检查域名是否可用

domains_available 方法返回True表示域名可用。

from namecheap import Api
api = Api('NamecheapUsername', 'YourNamecheapAPIKey', '12.34.56.78', sandbox=True, debug=True)
api.domains_available('taken.com', 'apsdjcpoaskdc.com')
# Might result in
# {
#   'taken.com' : False,
#   'apsdjcpoaskdc.com' : True
# }

# If you check a singular domain, it will return a bool, unless you pass force_dict=True
api.domains_available('taken.com')
# True
api.domains_available('taken.com', force_dict=True)
# {'taken.com' : False}

您还可以传递一个域名列表,在这种情况下,它会为所有域名进行批量检查,并返回一个包含答案的字典。您可能不应该使用此方法编写大规模域名检查工具,它旨在在注册域名之前使用。

CLI工具使用

首先,您需要编辑 ./credentials.py 文件以提供脚本的API访问权限。以下是一个示例

#!/usr/bin/env python

api_key = '0123456789abcdef0123456789abcdef'
username = 'myusername'
ip_address = '10.0.0.1'

然后,只需使用所需的参数调用脚本即可

./namecheap-api-cli --domain example.org --list

./namecheap-api-cli --domain example.org --add --type "A" --name "test" --address "127.0.0.1" --ttl 300
./namecheap-api-cli --domain example.org --add --type "CNAME" --name "alias-of-test" --address "test.example.org." --ttl 1800

./namecheap-api-cli --domain example.org --delete --type "CNAME" --name "alias-of-test" --address "test.example.org."
./namecheap-api-cli --domain example.org --delete --type "A" --name "test" --address "127.0.0.1"

基本主机记录管理代码

以下是一个简单的DNS记录管理脚本示例

#!/usr/bin/env python
"""
Define variables regarding to your API account:
  - api_key
  - username
  - ip_address
"""
from namecheap import Api

username = 'MyNamecheapUser'
api_key = 'SomeAPIKey'
ip_address = '1.2.3.4'
api = Api(username, api_key, ip_address, sandbox=False)

domain = "example.org"

# list domain records
api.list_records(domain)

# add an 'A' record for subdomain "test" pointing to 127.0.0.1
api.add_record(domain, 'A', '127.0.0.1', hostname='test', ttl=1800)

# delete record we just created,
# selecting it by Name, Type and Address values
api.delete_record(domain,  'A', '127.0.0.1', hostname='test')

重试机制

有时您可能会遇到错误的API响应,这可能与服务器端错误有关。

感谢 @gstein,我们实现了重试机制,可以通过向Api实例添加2个参数来启用它

api = Api(username, api_key, ip_address, sandbox=False,
          attempts_count=3,
          attempts_delay=0.1)

2或3的值应该可以解决问题。

更多

查看namecheap_tests.py以查看您可以执行的其他示例。

项目详情


下载文件

下载适用于您的平台的文件。如果您不确定选择哪个,请了解更多关于 安装包 的信息。

源分布

privex_namecheap-0.1.2.tar.gz (31.7 kB 查看散列)

上传于

构建分发

privex_namecheap-0.1.2-py3-none-any.whl (28.8 kB 查看哈希值)

上传于 Python 3

支持