# by 梁总,版权所有
import paramiko
import requests
import json
import time
from paramiko.ssh_exception import NoValidConnectionsError
from paramiko.ssh_exception import AuthenticationException
def dingding(text):
webhook = 'https://oapi.dingtalk.com/robot/send?access_token=1111111'
data = {
'msgtype': 'text',
'text': {'content': text},
'at': {
'atMobiles': ['13912111190','18501116069'],
'isAtAll': False
}
}
f = requests.post(webhook, data=json.dumps(data), headers={'Content-Type': 'application/json'})
class SSHConnection():
def __init__(self, hostname, port, username, password):
self.hostname = hostname
self.port = port
self.username = username
self.password = password
def connect(self):
self.ssh = paramiko.SSHClient()
self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.ssh.connect(hostname=self.hostname, port=self.port, username=self.username, password=self.password)
def run(self, input):
try:
self.connect()
except (AuthenticationException, NoValidConnectionsError, TimeoutError) as e:
print(e)
else:
output = self.cmd(input)
self.close()
return output
def cmd(self, input):
stdin, stdout, stderr = self.ssh.exec_command(input)
output = stdout.read().decode()
prompt = '[%s@MikroTik] > %s\n' % (self.username, input)
print(prompt + output)
# 第一个split是选择第3行,第二个split是返回第3列。
output1 = 'IP: ' + output.split('\r\n')[2].split()[2]
print(output1)
return output
def close(self):
self.ssh.close()
# ROS的IP是192.168.81.1,ssh的端口我更改为22022了,账号是abc,密码是123,接口我暂定是pppoe-out73和pppoe-out76,根据自己实际情况更改。
if __name__ == '__main__':
ssh = SSHConnection('192.168.81.1', 22022, 'abc', '123')
output = ssh.run('ip address print where interface=pppoe-out73')
output = ssh.run('ip address print where interface=pppoe-out76')
ssh.close()
# 发送到钉钉群,可以自己看情况
# dingding(output)