Python实现阿里云域名DDNS及SSH获取双栈路由器IPv4、IPv6地址
前言
本文参考了
https://developer.aliyun.com/article/755182?spm=a2c6h.13813017.0.dArticle738638.102c4d578Qrzce
https://developer.aliyun.com/article/712164?spm=a2c6h.13813017.0.dArticle738638.102c4d578Qrzce
参考文章并非本人所写,因为本人比较懒所以有些类似的就直接照搬了。如有侵权私信删除。
现在很多运营商面对家庭用户不提供公网IPv4地址仅提供IPv6公网地址。
本人恰巧负责某集团网络,已经提前向运营商申请了公网双栈及同时拥有公网IPv4地址以及公网IPv6地址。
本文章讲怎样通过阿里云的SDK来添加修改域名解析,检查本机IP与解析的IP是否一致,不一致自动修改解析,达到动态解析的目的,主要用于家庭宽带这些动态IP的地方。
同时基于华为路由器怎么获取固定IPv6地址及双栈网络设计做出一些分享。
部署前准备
0.首先得有一个阿里云的域名:
https://www.aliyun.com/minisite/goods?userCode=jdjc69nf
1.安装阿里云SDK和其他第三方库
pip install aliyun-python-sdk-core
pip install aliyun-python-sdk-alidns
pip install Paramiko
直接在CMD中输入上面的命令即可,如果下载速度太慢考虑更换pip源。
新建文本文档填充如下内容后重命名为pip.ini
后放入Windows用户目录,用户的根文件夹即可。
[global]
index-url = https://pypi.tuna.tsinghua.edu.cn/simple
[install]
trusted-host = https://pypi.tuna.tsinghua.edu.cn
使用Pycharm之类IDE的自行百度pycharm怎样安装第三方库
2.获取accessKeyId和accessSecret
可以在阿里云控制台个人中心直接获取,但是一般建议使用RAM角色来进行权限控制,这样这个accessKey和accessSecret就只能操作域名,不能操作其他的资源,相对会比较安全。
关于RAM快速入门:
https://help.aliyun.com/document_detail/28637.html?source=5176.11533457&userCode=jdjc69nf
本Python脚本需要accessKeyId具备如下权限
从这里开始
源码参考两位大神的代码增加了日志记录和SSH获取路由器IPv4和IPv6功能
如下
1.获取SSH获取华为设备IP地址
import paramiko
import re
import time
class ip:
username = 'admin' #设备用户名
password = 'admin' #设备密码
def ipv6(host, interface):
global ssh, ipv6_flag
ssh = paramiko.SSHClient()
ipv6_flag = 0
try:
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=host, port=22, username=ip.username, password=ip.password)
client = ssh.invoke_shell()
ipv6_flag = 1
except paramiko.AuthenticationException:
print("We had an authentication exception!")
except Exception as r:
print('未知错误 %s' % (r))
if ipv6_flag == 1:
def run_cmd(cmd, endswith): # 形参:cmd命令,结束符
buff = ''
client.send(cmd)
while not buff.endswith(endswith):
resp = str(client.recv(1024), 'utf-8')
buff += resp
return buff
run_cmd('display ipv6 int %s | include 240' % interface, '>')
ipv6 = run_cmd('\n', '>')
# print(ipv6)
ipv6_add = re.findall(r"(?<![:.\w])(?:[A-F0-9]{1,4}:){7}[A-F0-9]{1,4}(?![:.\w])", ipv6, re.I)
ipv6_add = (''.join(ipv6_add))
ssh.close()
return ipv6_add # ,ipv4_add
def ipv4(host, interface):
global ssh, ipv4_flag
ssh = paramiko.SSHClient()
ipv4_flag = 0
try:
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=host, port=22, username=ip.username, password=ip.password)
client = ssh.invoke_shell()
ipv4_flag = 1
except paramiko.AuthenticationException:
print("We had an authentication exception!")
except Exception as r:
print('未知错误 %s' % (r))
if ipv4_flag == 1:
def run_cmd(cmd, endswith): # 形参:cmd命令,结束符
buff = ''
client.send(cmd)
while not buff.endswith(endswith):
resp = str(client.recv