RouterOS之python調用API

本文主要講述官方提供的客戶端以及自己寫的增刪查改工具:

ros_tool.py?功能總匯,展示界面用了python的GUL,模塊用的為? tkinter? 模塊

其他文件為單個功能文件。

鏈接:https://pan.baidu.com/s/1_NIjG6gCQcnbp9Vwfi9Jyw 密碼:98ex

運行方式:python3? ros_tool.py? ip? username? password? ? (LINUX下,裝過ros,改為自己的?ip,用戶名,密碼?直接運行即可)


ros為python以及其他語言提供了接口,官方給出了一個? ?TCP客戶端的例子:


# !/usr/bin/env python3

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

import sys, time, binascii, socket, select

import hashlib

class ApiRos:

? ? "Routeros api"

? ? def __init__(self, sk):

? ? ? ? self.sk = sk

? ? ? ? self.currenttag = 0

? ? def login(self, username, pwd):

? ? ? ? for repl, attrs in self.talk(["/login"]):

? ? ? ? ? ? chal = binascii.unhexlify((attrs['=ret']).encode('UTF-8'))

? ? ? ? md = hashlib.md5()

? ? ? ? md.update(b'\x00')

? ? ? ? md.update(pwd.encode('UTF-8'))

? ? ? ? md.update(chal)

? ? ? ? self.talk(["/login", "=name=" + username,

? ? ? ? ? ? ? ? ? "=response=00" + binascii.hexlify(md.digest()).decode('UTF-8')])

? ? def talk(self, words):

? ? ? ? if self.writeSentence(words) == 0: return

? ? ? ? r = []

? ? ? ? while 1:

? ? ? ? ? ? i = self.readSentence();

? ? ? ? ? ? if len(i) == 0: continue

? ? ? ? ? ? reply = i[0]

? ? ? ? ? ? attrs = {}

? ? ? ? ? ? for w in i[1:]:

? ? ? ? ? ? ? ? j = w.find('=', 1)

? ? ? ? ? ? ? ? if (j == -1):

? ? ? ? ? ? ? ? ? ? attrs[w] = ''

? ? ? ? ? ? ? ? else:

? ? ? ? ? ? ? ? ? ? attrs[w[:j]] = w[j + 1:]

? ? ? ? ? ? r.append((reply, attrs))

? ? ? ? ? ? if reply == '!done': return r

? ? def writeSentence(self, words):

? ? ? ? ret = 0

? ? ? ? for w in words:

? ? ? ? ? ? self.writeWord(w)

? ? ? ? ? ? ret += 1

? ? ? ? self.writeWord('')

? ? ? ? return ret

? ? def readSentence(self):

? ? ? ? r = []

? ? ? ? while 1:

? ? ? ? ? ? w = self.readWord()

? ? ? ? ? ? if w == '': return r

? ? ? ? ? ? r.append(w)

? ? def writeWord(self, w):

? ? ? ? print(("<<< " + w))

? ? ? ? self.writeLen(len(w))

? ? ? ? self.writeStr(w)

? ? def readWord(self):

? ? ? ? ret = self.readStr(self.readLen())

? ? ? ? print((">>> " + ret))

? ? ? ? return ret

? ? def writeLen(self, l):

? ? ? ? if l < 0x80:

? ? ? ? ? ? self.writeStr(chr(l))

? ? ? ? elif l < 0x4000:

? ? ? ? ? ? l |= 0x8000

? ? ? ? ? ? self.writeStr(chr((l >> 8) & 0xFF))

? ? ? ? ? ? self.writeStr(chr(l & 0xFF))

? ? ? ? elif l < 0x200000:

? ? ? ? ? ? l |= 0xC00000

? ? ? ? ? ? self.writeStr(chr((l >> 16) & 0xFF))

? ? ? ? ? ? self.writeStr(chr((l >> 8) & 0xFF))

? ? ? ? ? ? self.writeStr(chr(l & 0xFF))

? ? ? ? elif l < 0x10000000:

? ? ? ? ? ? l |= 0xE0000000

? ? ? ? ? ? self.writeStr(chr((l >> 24) & 0xFF))

? ? ? ? ? ? self.writeStr(chr((l >> 16) & 0xFF))

? ? ? ? ? ? self.writeStr(chr((l >> 8) & 0xFF))

? ? ? ? ? ? self.writeStr(chr(l & 0xFF))

? ? ? ? else:

? ? ? ? ? ? self.writeStr(chr(0xF0))

? ? ? ? ? ? self.writeStr(chr((l >> 24) & 0xFF))

? ? ? ? ? ? self.writeStr(chr((l >> 16) & 0xFF))

? ? ? ? ? ? self.writeStr(chr((l >> 8) & 0xFF))

? ? ? ? ? ? self.writeStr(chr(l & 0xFF))

? ? def readLen(self):

? ? ? ? c = ord(self.readStr(1))

? ? ? ? if (c & 0x80) == 0x00:

? ? ? ? ? ? pass

? ? ? ? elif (c & 0xC0) == 0x80:

? ? ? ? ? ? c &= ~0xC0

? ? ? ? ? ? c <<= 8

? ? ? ? ? ? c += ord(self.readStr(1))

? ? ? ? elif (c & 0xE0) == 0xC0:

? ? ? ? ? ? c &= ~0xE0

? ? ? ? ? ? c <<= 8

? ? ? ? ? ? c += ord(self.readStr(1))

? ? ? ? ? ? c <<= 8

? ? ? ? ? ? c += ord(self.readStr(1))

? ? ? ? elif (c & 0xF0) == 0xE0:

? ? ? ? ? ? c &= ~0xF0

? ? ? ? ? ? c <<= 8

? ? ? ? ? ? c += ord(self.readStr(1))

? ? ? ? ? ? c <<= 8

? ? ? ? ? ? c += ord(self.readStr(1))

? ? ? ? ? ? c <<= 8

? ? ? ? ? ? c += ord(self.readStr(1))

? ? ? ? elif (c & 0xF8) == 0xF0:

? ? ? ? ? ? c = ord(self.readStr(1))

? ? ? ? ? ? c <<= 8

? ? ? ? ? ? c += ord(self.readStr(1))

? ? ? ? ? ? c <<= 8

? ? ? ? ? ? c += ord(self.readStr(1))

? ? ? ? ? ? c <<= 8

? ? ? ? ? ? c += ord(self.readStr(1))

? ? ? ? return c

? ? def writeStr(self, str):

? ? ? ? n = 0;

? ? ? ? while n < len(str):

? ? ? ? ? ? r = self.sk.send(bytes(str[n:], 'UTF-8'))

? ? ? ? ? ? if r == 0: raise RuntimeError("connection closed by remote end")

? ? ? ? ? ? n += r

? ? def readStr(self, length):

? ? ? ? ret = ''

? ? ? ? while len(ret) < length:

? ? ? ? ? ? s = self.sk.recv(length - len(ret))

? ? ? ? ? ? if s == '': raise RuntimeError("connection closed by remote end")

? ? ? ? ? ? ret += s.decode('UTF-8', 'replace')

? ? ? ? return ret

def main():

? ? s = None

? ? for res in socket.getaddrinfo(sys.argv[1], "8728", socket.AF_UNSPEC, socket.SOCK_STREAM):

? ? ? ? af, socktype, proto, canonname, sa = res

? ? ? ? try:

? ? ? ? ? ? s = socket.socket(af, socktype, proto)

? ? ? ? except (socket.error, msg):

? ? ? ? ? ? s = None

? ? ? ? ? ? continue

? ? ? ? try:

? ? ? ? ? ? s.connect(sa)

? ? ? ? except (socket.error, msg):

? ? ? ? ? ? s.close()

? ? ? ? ? ? s = None

? ? ? ? ? ? continue

? ? ? ? break

? ? if s is None:

? ? ? ? print('could not open socket')

? ? ? ? sys.exit(1)

? ? apiros = ApiRos(s);

? ? apiros.login(sys.argv[2], sys.argv[3]);

? ? #模擬用戶自己輸入代碼進行api控制

? ? tmpcommand=input('請輸入你想查詢的命令')

? ? inputsentence = []

? ? inputsentence.append(tmpcommand)

? ? apiros.writeSentence(inputsentence)

? ? while 1:

? ? ? ? x = apiros.readSentence()

? ? ? ? #print(x)

? ? ? ? if x == ['!done'] or x==['!re', '=status=finished']:

? ? ? ? ? ? break

? ? #導出ros配置到ROS本地ghg1.rsc文件

? ? # inputsentence = []

? ? #

? ? # inputsentence.append('/export')

? ? # inputsentence.append('=file=ghg1.rsc')

? ? # apiros.writeSentence(inputsentence)

? ? # while 1:

? ? #? ? x = apiros.readSentence()

? ? #? ? #print(x)

? ? #? ? if x == ['!done'] or x==['!re', '=status=finished']:

? ? #? ? ? ? break

? ? #從ros上傳文件到ftp的代碼

? ? # inputsentence = []

? ? # inputsentence.append('/tool/fetch')

? ? # inputsentence.append('=address=192.168.0.108')

? ? # inputsentence.append('=src-path=ghg1.rsc')

? ? # inputsentence.append('=user=xxxxx')

? ? # inputsentence.append('=mode=ftp')

? ? # inputsentence.append('=password=xxxxx')

? ? # inputsentence.append('=dst-path=123.rsc')

? ? # inputsentence.append('=upload=yes')

? ? # apiros.writeSentence(inputsentence)

? ? # inputsentence = []

? ? # while 1:

? ? #? ? x = apiros.readSentence()

? ? #? ? #print(x)

? ? #? ? if x == ['!done'] or x==['!re', '=status=finished']:

? ? #? ? ? ? break

? ? #刪除文件代碼

? ? # inputsentence = []

? ? # inputsentence.append('/file/remove')

? ? # inputsentence.append('=numbers=ghg1.rsc')

? ? # apiros.writeSentence(inputsentence)

? ? # while 1:

? ? #? ? x = apiros.readSentence()

? ? #? ? print(x)

? ? #? ? if x == ['!done'] or x==['!re', '=status=finished']:

? ? #? ? ? ? break

? ? ? ? ? ? #官方循環代碼,等待你輸入命令行,可以用來測試代碼命令行

? ? ? ? ? ? # while 1:

? ? ? ? ? ? #? ? r = select.select([s, sys.stdin], [], [], None)

? ? ? ? ? ? #? ? if s in r[0]:

? ? ? ? ? ? #? ? ? ? # something to read in socket, read sentence

? ? ? ? ? ? #? ? ? ? x = apiros.readSentence()

? ? ? ? ? ? #

? ? ? ? ? ? #? ? if sys.stdin in r[0]:

? ? ? ? ? ? #? ? ? ? # read line from input and strip off newline

? ? ? ? ? ? #? ? ? ? l = sys.stdin.readline()

? ? ? ? ? ? #? ? ? ? print(l)

? ? ? ? ? ? #? ? ? ? l = l[:-1]

? ? ? ? ? ? #? ? ? ? print(l)

? ? ? ? ? ? #

? ? ? ? ? ? #

? ? ? ? ? ? #? ? ? ? # if empty line, send sentence and start with new

? ? ? ? ? ? #? ? ? ? # otherwise append to input sentence

? ? ? ? ? ? #? ? ? ? if l == '':

? ? ? ? ? ? #? ? ? ? ? ? apiros.writeSentence(inputsentence)

? ? ? ? ? ? #? ? ? ? ? ? inputsentence = []

? ? ? ? ? ? #? ? ? ? else:

? ? ? ? ? ? #? ? ? ? ? ? inputsentence.append(l)

if __name__ == '__main__':

? ? main()

下面是本人寫的一個小工具,可以進行路由的增刪改查,代碼有很多不足之處,刪除功能時?容易出現問題,做了死循環,根據時間控制結束,性能非常低,有興趣的可以改下:

運行方式:python3? ros_tool.py? ip? username? password? ? (LINUX下,裝過ros,改為自己的?ip,用戶名,密碼?直接運行即可)

# !/usr/bin/env python

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

# Author:yhq

import sys, time, binascii, socket, select

from datetimeimport datetime

# import posix,

import hashlib

from tkinterimport *

# import subprocess

root = Tk()

root.title("ros工具")

root.geometry('1100x800')

class ApiRos:

"Routeros api"

? ? def __init__(self, sk):

"""

初始化函數

? ? ? ? :paramsk:

"""

? ? ? ? self.sk = sk

self.currenttag =0

? ? def login(self, username, pwd):

"""

登錄函數

? ? ? ? :paramusername:

? ? ? ? :parampwd:

? ? ? ? :return:

"""

? ? ? ? for repl, attrsin self.talk(["/login"]):

chal = binascii.unhexlify((attrs['=ret']).encode('UTF-8'))

# 對 pwd 進行加密

? ? ? ? md = hashlib.md5()

md.update(b'\x00')

md.update(pwd.encode('UTF-8'))

md.update(chal)

self.talk(["/login", "=name=" + username,

? ? ? ? ? ? ? ? ? "=response=00" + binascii.hexlify(md.digest()).decode('UTF-8')])

def talk(self, words):

"""

? ? ? ? :paramwords:

? ? ? ? :return:

"""

? ? ? ? if self.writeSentence(words) ==0:

return

? ? ? ? r = []

while 1:

# python2 中? while 1 比 while True 執行速度快? 大概快1/3? python3中兩者基本沒區別

? ? ? ? ? ? i =self.readSentence()

if len(i) ==0:

continue

? ? ? ? ? ? reply = i[0]

attrs = {}

for win i[1:]:

j = w.find('=', 1)

if j == -1:

attrs[w] =''

? ? ? ? ? ? ? ? else:

attrs[w[:j]] = w[j +1:]

r.append((reply, attrs))

if reply =='!done':

return r

def writeSentence(self, words):

"""

? ? ? ? :paramwords:

? ? ? ? :return:

"""

? ? ? ? ret =0

? ? ? ? for win words:

self.writeWord(w)

ret +=1

? ? ? ? self.writeWord('')

return ret

def readSentence(self):

"""

? ? ? ? :return:

"""

? ? ? ? r = []

while 1:

w =self.readWord()

if w =='':

return r

r.append(w)

def writeWord(self, w):

"""

? ? ? ? :paramw:

? ? ? ? :return:

"""

? ? ? ? print(("<<< " + w))

self.writeLen(len(w))

self.writeStr(w)

def readWord(self):

"""

? ? ? ? :return:

"""

? ? ? ? ret =self.readStr(self.readLen())

print((">>> " + ret))

return ret

def writeLen(self, l):

"""

? ? ? ? :paraml:

? ? ? ? :return:

"""

? ? ? ? if l <0x80:

self.writeStr(chr(l))

elif l <0x4000:

l |=0x8000

? ? ? ? ? ? self.writeStr(chr((l >>8) &0xFF))

self.writeStr(chr(l &0xFF))

elif l <0x200000:

l |=0xC00000

? ? ? ? ? ? self.writeStr(chr((l >>16) &0xFF))

self.writeStr(chr((l >>8) &0xFF))

self.writeStr(chr(l &0xFF))

elif l <0x10000000:

l |=0xE0000000

? ? ? ? ? ? self.writeStr(chr((l >>24) &0xFF))

self.writeStr(chr((l >>16) &0xFF))

self.writeStr(chr((l >>8) &0xFF))

self.writeStr(chr(l &0xFF))

else:

self.writeStr(chr(0xF0))

self.writeStr(chr((l >>24) &0xFF))

self.writeStr(chr((l >>16) &0xFF))

self.writeStr(chr((l >>8) &0xFF))

self.writeStr(chr(l &0xFF))

def readLen(self):

"""

? ? ? ? :return:

"""

? ? ? ? c =ord(self.readStr(1))

if (c &0x80) ==0x00:

pass

? ? ? ? elif (c &0xC0) ==0x80:

c &= ~0xC0

? ? ? ? ? ? c <<=8

? ? ? ? ? ? c +=ord(self.readStr(1))

elif (c &0xE0) ==0xC0:

c &= ~0xE0

? ? ? ? ? ? c <<=8

? ? ? ? ? ? c +=ord(self.readStr(1))

c <<=8

? ? ? ? ? ? c +=ord(self.readStr(1))

elif (c &0xF0) ==0xE0:

c &= ~0xF0

? ? ? ? ? ? c <<=8

? ? ? ? ? ? c +=ord(self.readStr(1))

c <<=8

? ? ? ? ? ? c +=ord(self.readStr(1))

c <<=8

? ? ? ? ? ? c +=ord(self.readStr(1))

elif (c &0xF8) ==0xF0:

c =ord(self.readStr(1))

c <<=8

? ? ? ? ? ? c +=ord(self.readStr(1))

c <<=8

? ? ? ? ? ? c +=ord(self.readStr(1))

c <<=8

? ? ? ? ? ? c +=ord(self.readStr(1))

return c

def writeStr(self, str):

"""

? ? ? ? :paramstr:

? ? ? ? :return:

"""

? ? ? ? n =0

? ? ? ? while n

r =self.sk.send(bytes(str[n:], 'UTF-8'))

if r ==0:

raise RuntimeError("connection closed by remote end")

n += r

def readStr(self, length):

"""

? ? ? ? :paramlength:

? ? ? ? :return:

"""

? ? ? ? ret =''

? ? ? ? while len(ret) < length:

s =self.sk.recv(length -len(ret))

if s =='':

raise RuntimeError("connection closed by remote end")

ret += s.decode('UTF-8', 'replace')

return ret

def check_interface():

"""

查看interface

? ? :return:

"""

? ? s =None

? ? for resin socket.getaddrinfo(sys.argv[1], "8728", socket.AF_UNSPEC, socket.SOCK_STREAM):

af, socktype, proto, canonname, sa = res

try:

s = socket.socket(af, socktype, proto)

except socket.error:

s =None

continue

? ? ? ? try:

s.connect(sa)

except socket.error:

s.close()

s =None

continue

break

? ? if sis None:

print('could not open socket')

sys.exit(1)

global apiros

apiros = ApiRos(s)

apiros.login(sys.argv[2], sys.argv[3])

ls = ['/interface/print', '=.proplist=name']

apiros.writeSentence(ls)

ls1 = []

while 1:

x = apiros.readSentence()

if len(x) >1:

ls1.append(x[1][6:])

if x == ['!done']or x == ['!re', '=status=finished']:

break

? ? # print('可用interface名字:%s' % ls1)

? ? te.insert('1.0', " 可用interface名字: %s\n" % ls1)

te.insert('1.0', "*******************************\n")

l1 = Label(root, text="輸入interface名:")

l1.pack()# 這里的side可以賦值為LEFT? RIGHT TOP? BOTTOM

? ? global xls

xls = Entry()

xls.pack()

l2 = Label(root, text="輸入ip地址段前三位(如192.168.3):")

l2.pack()# 這里的side可以賦值為LEFT? RTGHT TOP? BOTTOM

? ? global sheet

sheet = Entry()

sheet.pack()

def add_ip():

n =0

? ? t1 = time.time()

interface = xls.get()

ip = sheet.get()

for iin range(0, 25):

address ='%s.%s/24' % (ip, i)

network ='%s.0' % ip

inputsentence = ['/ip/address/add', '=address=%s' % address, '=interface=%s' % interface,

? ? ? ? ? ? ? ? ? ? ? ? '=network=%s' % network, '=comment=%s %s' % (address, interface)]

apiros.writeSentence(inputsentence)

x = apiros.readSentence()

# print("添加address:%s成功" % address)

? ? ? ? te.insert('1.0', "添加ip:%s成功\n" % address)

n +=1

? ? t2 = time.time()

t = t2 - t1

# print('添加ip數量:%s' % n)

? ? te.insert('1.0', "添加ip數量:%s\n" % n)

print('添加ip用時:%s' % t)

te.insert('1.0', "添加ip用時:%s\n" % t)

te.insert('1.0', "*******************************\n")

def remove_ip():

"""

批量刪除ip

? ? :return:

"""

? ? s =None

? ? for resin socket.getaddrinfo(sys.argv[1], "8728", socket.AF_UNSPEC, socket.SOCK_STREAM):

af, socktype, proto, canonname, sa = res

try:

s = socket.socket(af, socktype, proto)

except socket.error:

s =None

continue

? ? ? ? try:

s.connect(sa)

except socket.error:

s.close()

s =None

continue

break

? ? if sis None:

print('could not open socket')

sys.exit(1)

apiros = ApiRos(s)

apiros.login(sys.argv[2], sys.argv[3])

# 批量刪除ip

? ? global count

count = -1

? ? global n

n =0

? ? inputsentence = ['/ip/address/print', '=.proplist=.id,comment']

apiros.writeSentence(inputsentence)

while 1:

x = apiros.readSentence()

count +=1

? ? ? ? if len(x) >2:

# x[1]為ip 的 id

? ? ? ? ? ? while 1:

inputsentence = ['/ip/address/remove', x[1]]

apiros.writeSentence(inputsentence)

y = apiros.readSentence()

n +=1

? ? ? ? ? ? ? ? if y == ['!done']or y == ['!re', '=status=finished']:

break

? ? ? ? ? ? # print("刪除%s成功" % x[2])

? ? ? ? ? ? te.insert('1.0', "刪除ip:%s成功\n" % x[2])

else:

pass

? ? ? ? if x == ['!done']or x == ['!re', '=status=finished']:

break

def start_remove_ip():

"""

執行remove_ip

? ? :return:

"""

? ? t1 = time.time()

while 1:

remove_ip()

if n ==0:

break

? ? t2 = time.time()

t = t2 - t1

# print('剩余ip總數:%s' % count)

? ? te.insert('1.0', "剩余ip總數:%s成功\n" % count)

# print('刪除ip用時:%s' % t)

? ? te.insert('1.0', "刪除ip用時:%s\n" % t)

te.insert('1.0', "*******************************\n")

def backup():

"""

備份設備

? ? :return:

"""

? ? s =None

? ? for resin socket.getaddrinfo(sys.argv[1], "8728", socket.AF_UNSPEC, socket.SOCK_STREAM):

af, socktype, proto, canonname, sa = res

try:

s = socket.socket(af, socktype, proto)

except socket.error:

s =None

continue

? ? ? ? try:

s.connect(sa)

except socket.error:

s.close()

s =None

continue

break

? ? if sis None:

print('could not open socket')

sys.exit(1)

apiros = ApiRos(s)

apiros.login(sys.argv[2], sys.argv[3])

inputsentence = []

inputsentence.append('/system/backup/save')

# 按日期生成文件名

? ? filename = datetime.now().strftime('%Y%m%d %H%M%S')

inputsentence.append(' =name=%s.backup' % filename)

apiros.writeSentence(inputsentence)

while 1:

x = apiros.readSentence()

print(x)

if x == ['!done']or x == ['!re', '=status=finished']:

# print("備份成功")

? ? ? ? ? ? te.insert('1.0', "備份:%s.backup成功\n" % filename)

break

? ? te.insert('1.0', "*******************************\n")

def check_ip():

"""

查看ip

? ? :return:

"""

? ? s =None

? ? for resin socket.getaddrinfo(sys.argv[1], "8728", socket.AF_UNSPEC, socket.SOCK_STREAM):

af, socktype, proto, canonname, sa = res

try:

s = socket.socket(af, socktype, proto)

except socket.error:

s =None

continue

? ? ? ? try:

s.connect(sa)

except socket.error:

s.close()

s =None

continue

break

? ? if sis None:

print('could not open socket')

sys.exit(1)

apiros = ApiRos(s)

apiros.login(sys.argv[2], sys.argv[3])

# 查看ip

? ? inputsentence = ['/ip/address/print', ]

apiros.writeSentence(inputsentence)

count1 = -1

? ? while 1:

x = apiros.readSentence()

count1 +=1

? ? ? ? if x == ['!done']or x == ['!re', '=status=finished']:

break

? ? print('ip總數:%s' % count1)

te.insert('1.0', "ip總數:%s\n" % count1)

te.insert('1.0', "*******************************\n")

def check_route():

"""

查看route

? ? :return:

"""

? ? s =None

? ? for resin socket.getaddrinfo(sys.argv[1], "8728", socket.AF_UNSPEC, socket.SOCK_STREAM):

af, socktype, proto, canonname, sa = res

try:

s = socket.socket(af, socktype, proto)

except socket.error:

s =None

continue

? ? ? ? try:

s.connect(sa)

except socket.error:

s.close()

s =None

continue

break

? ? if sis None:

print('could not open socket')

sys.exit(1)

apiros = ApiRos(s)

apiros.login(sys.argv[2], sys.argv[3])

# 查看route

? ? inputsentence = ['/ip/route/print', ]

apiros.writeSentence(inputsentence)

count2 = -1

? ? while 1:

x = apiros.readSentence()

count2 +=1

? ? ? ? if x == ['!done']or x == ['!re', '=status=finished']:

break

? ? # print('route總數:%s' % count2)

? ? te.insert('1.0', "route總數:%s\n" % count2)

te.insert('1.0', "*******************************\n")

def add_route():

"""

批量添加route

? ? :return:

"""

? ? gateway = xls.get()

ip = sheet.get()

for iin range(0, 10):

dst_address ='%s.%s.0/24' % (ip[:ip.rfind('.')], i)

# pref_src = '%s.%s.%s' % (ip, i, i)

? ? ? ? inputsentence = ['/ip/route/add', '=dst-address=%s' % dst_address, '=gateway=%s' % gateway,

? ? ? ? ? ? ? ? ? ? ? ? '=comment=%s ' % dst_address]

apiros.writeSentence(inputsentence)

x = apiros.readSentence()

# print("添加route:%s成功" % dst_address)

? ? ? ? te.insert('1.0', "添加route:%s成功\n" % dst_address)

te.insert('1.0', "*******************************\n")

def remove_route():

"""

批量刪除route

? ? :return:

"""

? ? s =None

? ? for resin socket.getaddrinfo(sys.argv[1], "8728", socket.AF_UNSPEC, socket.SOCK_STREAM):

af, socktype, proto, canonname, sa = res

try:

s = socket.socket(af, socktype, proto)

except socket.error:

s =None

continue

? ? ? ? try:

s.connect(sa)

except socket.error:

s.close()

s =None

continue

break

? ? if sis None:

print('could not open socket')

sys.exit(1)

apiros = ApiRos(s)

apiros.login(sys.argv[2], sys.argv[3])

# 批量刪除route

? ? global count

count = -1

? ? global n

n =0

? ? inputsentence = ['/ip/route/print', '?>comment=', '=.proplist=.id,gateway']

apiros.writeSentence(inputsentence)

while 1:

x = apiros.readSentence()

count +=1

? ? ? ? if len(x) ==3:

inputsentence = ['/ip/route/remove', x[1]]

apiros.writeSentence(inputsentence)

y = apiros.readSentence()

n +=1

? ? ? ? ? ? # print ("刪除%s成功" % x[2])

? ? ? ? ? ? te.insert('1.0', "刪除%s成功\n" % x[2])

if x == ['!done']or x == ['!re', '=status=finished']:

break

def start_remove_route():

"""

執行 remove_route

? ? :return:

"""

? ? t1 = time.time()

t2 = t1 +15

? ? while 1:

remove_route()

t3 = time.time()

if t3 > t2:

te.insert('1.0', "*******************************\n")

break

def remove_re():

"""

route去重

? ? :return:

"""

? ? s =None

? ? for resin socket.getaddrinfo(sys.argv[1], "8728", socket.AF_UNSPEC, socket.SOCK_STREAM):

af, socktype, proto, canonname, sa = res

try:

s = socket.socket(af, socktype, proto)

except socket.error:

s =None

continue

? ? ? ? try:

s.connect(sa)

except socket.error:

s.close()

s =None

continue

break

? ? if sis None:

print('could not open socket')

sys.exit(1)

apiros = ApiRos(s)

apiros.login(sys.argv[2], sys.argv[3])

# 批量刪除重復route

? ? global count

count = -1

? ? global n

n =0

? ? inputsentence = ['/ip/route/print', '?=active=false', '=.proplist=.id,gateway']

apiros.writeSentence(inputsentence)

while 1:

x = apiros.readSentence()

count +=1

? ? ? ? if len(x) ==3:

inputsentence = ['/ip/route/remove', x[1]]

apiros.writeSentence(inputsentence)

y = apiros.readSentence()

n +=1

? ? ? ? ? ? # print("刪除%s成功" % x[2])

? ? ? ? ? ? te.insert('1.0', "去重%s成功\n" % x[2])

if x == ['!done']or x == ['!re', '=status=finished']:

break

def start_remove_re():

"""

執行remove_re

? ? :return:

"""

? ? t1 = time.time()

t2 = t1 +15

? ? while 1:

remove_re()

t3 = time.time()

if t3 > t2:

te.insert('1.0', "*******************************\n")

break

te = Text()

te.pack()

Button(root, text="備份設備", bg='green', command=backup).pack(padx=10, pady=10, ipadx=3, side=LEFT)

Button(root, text="查看可用interface", bg='green', command=check_interface).pack(padx=5,? pady=20, side=LEFT)

Button(root, text="查看ip", bg='green', command=check_ip).pack(padx=5, pady=10,? ipadx=3, side=LEFT)

Button(root, text="查看route", bg='green', command=check_route).pack(padx=5,? pady=15, ipadx=3, side=LEFT)

Button(root, text="刪除ip", bg='#ff3300', command=start_remove_ip).pack(padx=5, pady=10,? ipadx=3, side=RIGHT)

Button(root, text="刪除route", bg='#ff3300', command=start_remove_route).pack(padx=5,? pady=10, ipadx=3, side=RIGHT)

Button(root, text="route去重", bg='#ff3300', command=start_remove_re).pack(padx=5,? pady=10, ipadx=3, side=RIGHT)

Button(root, text="增加ip", bg='#9900ff', command=add_ip).pack(padx=5, pady=10,? ipadx=3,? side=RIGHT)

Button(root, text="增加route", bg='#9900ff', command=add_route).pack(padx=5, pady=10, ipadx=3, side=RIGHT)

root.mainloop()

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,606評論 6 533
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,582評論 3 418
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,540評論 0 376
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,028評論 1 314
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,801評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,223評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,294評論 3 442
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,442評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,976評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,800評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,996評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,543評論 5 360
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,233評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,662評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,926評論 1 286
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,702評論 3 392
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,991評論 2 374

推薦閱讀更多精彩內容

  • 學習新東西當要用到我們的3W方法了(what why how),下面我們來學習下ros的api, 地址:https...
    追尋823閱讀 9,823評論 0 0
  • http://python.jobbole.com/85231/ 關于專業技能寫完項目接著寫寫一名3年工作經驗的J...
    燕京博士閱讀 7,603評論 1 118
  • Python 面向對象Python從設計之初就已經是一門面向對象的語言,正因為如此,在Python中創建一個類和對...
    順毛閱讀 4,232評論 4 16
  • 今天是我每天一篇文章的第120篇。 這兩天才知道一個消息,一家電商公司準備解散了,因為這個公司跟我頗有淵源...
    很溫暖閱讀 195評論 0 0
  • 【奇談雜閱】農歷雞年來了。找了一下關于雞的成語,發現很多都和狗在一起——雞飛狗跳,雞鳴狗盜,偷雞摸狗,斗雞走狗,雞...
    奇妙的奇閱讀 162評論 0 0