1.程序制作原因:
需要定位RouterOS路由器是否在线,并统计pppoe故障的拨号数目
2.所需环境:
windows7,python3.6
3.实现方式:
通过ssh发送命令
4.实现功能:
①判断RouterOS路由器是否在线
②统计各个RouterOS路由器pppoe故障的拨号数目
③将获取到的数据钉钉群通知
5.完整代码如下(branch_pppoe_detection.py):
import paramiko
import threading
import json
import requests
import os
import datetime
import time
# 定义存储结果的数组
# re_result = []
out_result = []
falt_area = []
# 钉钉群通知
def inotice(content):
# webhook请替换为你实际的钉钉群api链接
webhook = 'xxxx'
data = {
"msgtype": "text",
"text": {
"content": content
}
}
headers = {'Content-Type': 'application/json'}
result = requests.post(url=webhook, data=json.dumps(data), headers=headers)
def ssh_connect(host_ip, host_port, user_name, password, command, city):
# SSH远程连接
ssh = paramiko.SSHClient() # 创建sshclient
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 指定当对方主机没有本机公钥的情况时应该怎么办,AutoAddPolicy表示自动在对方主机保存下本机的秘钥
ssh.connect(host_ip, host_port, user_name, password, timeout=5, allow_agent=False, look_for_keys=False)
# 执行命令并获取执行结果
stdin, stdout, stderr = ssh.exec_command(command)
out = stdout.readlines()
err = stderr.readlines()
for i in out:
message = str(host_ip) + " " + city + " " + str(i).strip('\r\n')
out_result.append(message)
ssh.close()
def operation(user_name, password, host_port, host_ip, command, city):
try:
ssh_connect(host_ip, host_port, user_name, password, command, city)
except Exception as e:
content = host_ip + " " + city + " " + str(e)
# re_result.append(content)
out_result.append(content)
def main():
# 存储routeros的管理地址
iplist = []
# 存储账号,密码,端口信息
auth = []
dir = os.getcwd()
dir_iplist = os.path.join(dir, "iplist.txt")
dir_auth = os.path.join(dir, "auth.txt")
# 读取routeros的管理地址
if os.path.isfile(dir_iplist):
with open(dir_iplist, "r") as f:
for line in f.readlines():
iplist.append(line.strip("\n"))
# 读取账号,密码,端口信息
if os.path.isfile(dir_auth):
with open(dir_auth, "r") as f:
for line in f.readlines():
# print(line.strip("\n"))
auth.append(line.strip("\n"))
# 定义线程数组
threads = []
# 获取权限
u_name = auth[0]
u_pass = auth[1]
u_port = auth[2]
# 定义执行的命令
command = ':gl lt 0;/interface pppoe-cl;:foreach i in [find] do={:if [get $i running ] do={} else={:set lt ($lt+1)}};:put $lt'
for i in iplist:
# print(i)
data = i.split('\t')
print(data)
ip = data[0]
# print(ip)
city = data[1]
th = threading.Thread(target=operation, args=(u_name, u_pass, u_port, ip, command, city,))
th.setDaemon(True)
th.start()
threads.append(th)
# 关闭所有子线程
for th in threads:
th.join()
for i in out_result:
arry = i.split(" ")
# print(type(arry[2]))
if arry[2] != "0":
falt_area.append(i)
# 数组不为空则有故障,则发送钉钉通知
if len(falt_area) != 0:
now_time = datetime.datetime.now().strftime('%Y-%m-%d %R')
falt_area.sort(key=lambda i: (int(i.split('.')[2]), int(i.split('.')[3].split(' ')[0])))
falt = '\n'.join(falt_area)
falt_area.clear()
falt = now_time + ' 地区故障拨数\n' + falt
print(falt)
inotice(falt)
out_result.clear()
if __name__ == '__main__':
while True:
main()
time.sleep(900)

1万+

被折叠的 条评论
为什么被折叠?



