当前位置: 首页 > 工具软件 > dnspod-python > 使用案例 >

linux 用api读取本机ip,dnspod通过接口解析本地ip python脚本

裴兴学
2023-12-01

最近内网搭建了一台gitlab服务器,因为是内网没有公网ip,为了方便同事访问,dnspod直接解析了内网ip

但是网卡使用的是dhcp的获取ip的,每次关机可能会导致ip变动,所以通过dnspod接口改写了官方脚本来实现自动解析!

下面是我改下的脚本,你也可以把他写到计划任务里面多少分钟或小时执行一次!#!/usr/bin/env python2

# -*- coding:utf-8 -*-

import httplib

import urllib

import socket

import time

# Use Token, check https://support.dnspod.cn/Kb/showarticle/tsid/227/

ID = "秘钥里面设置获取到" # relace with yours, get it as link above show you.

Token = "秘钥里面设置获取到" # relace with yours, get it as above link show you.

#

params = dict(

login_token=("%s,%s" % (ID, Token)),

format="json",

domain_id=通过curl获取到, # replace with your domain_od, can get it by API Domain.List

# curl https://dnsapi.cn/Domain.List -d "login_token=你的id,Token&format=json"

record_id=通过curl获取到, # replace with your record_id, can get it by API Record.List

#curl 'https://dnsapi.cn/Record.List' -d 'login_token=你的id,Token&format=json&domain_id=上面获取到的'

sub_domain="dev", # replace with your sub_domain

record_line="默认", #

)

current_ip = None

def ddns(ip):

params.update(dict(value=ip))

headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/json"}

conn = httplib.HTTPSConnection("dnsapi.cn")

conn.request("POST", "/Record.Ddns", urllib.urlencode(params), headers)

response = conn.getresponse()

print response.status, response.reason

data = response.read()

print data

conn.close()

return response.status == 200

#获取本机ip

def getip():

try:

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

s.connect(('8.8.8.8', 80))

ip = s.getsockname()[0]

finally:

s.close()

return ip

if __name__ == '__main__':

while True:

try:

ip = getip()

print ip

if current_ip != ip:

if ddns(ip):

current_ip = ip

except Exception as e:

print e

pass

time.sleep(30)

 类似资料: