sshLib.py
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
from netmiko import ConnectHandler
class SSHLib(object):
def __init__(self, manufacturer, ssh_ip, ssh_port, ssh_username, ssh_password):
manufacturer_list = ['huawei', 'h3c']
if manufacturer not in manufacturer_list:
raise ValueError('Device manufacturer is error.')
self.data = None
self.cursor = None
self.output = ''
link_device_params = {
'ip': ssh_ip,
'port': ssh_port,
'username': ssh_username,
'password': ssh_password,
'device_type': 'hp_comware' if manufacturer == 'h3c' else manufacturer
}
self.cursor = ConnectHandler(**link_device_params)
def get_cir(self, port):
command = 'display qos policy interface %s' % port
output = self.cursor.send_command(command)
# print(output)
output = [i for i in output.split('\n') if 'Policy:' in i or 'Behavior:' in i or 'CIR' in i]
# print(output)
output = [i for i in ','.join(output).replace('CIR', 'CIR:').replace(' ', '').split(',') if ':' in i]
# print(output)
output = {i.split(':')[0].lower(): i.split(':')[1].replace('(kbps)', '') for i in set(output)}
output['cir'] = int(output['cir'])
# print(output)
return output
def set_cir(self, behavior, cir):
if 1000 <= cir <= 4000:
cbs = 192000
elif 5000 <= cir <= 9000:
cbs = 960000
elif 10000 <= cir <= 19000:
cbs = 1920000
elif 20000 <= cir <= 29000:
cbs = 3840000
elif 30000 <= cir <= 39000:
cbs = 5760000
elif 40000 <= cir <= 49000:
cbs = 7680000
elif 50000 <= cir <= 59000:
cbs = 9600000
elif 60000 <= cir <= 69000:
cbs = 11520000
elif 70000 <= cir <= 79000:
cbs = 13440000
elif 80000 <= cir <= 82000:
cbs = 15360000
elif 83000 <= cir:
cbs = 16000000
else:
cbs = 16000000
commands = [
'traffic behavior %s' % behavior,
'car cir %s cbs %s ebs %s green pass red discard yellow pass' % (cir, cbs, cbs)
]
try:
self.output = self.cursor.send_config_set(commands)
if '^' in self.output:
return False
else:
return True
except BaseException as e:
raise ValueError('commands run is error. [ERROR INFO]: %s' % e)
@property
def logs(self):
return self.output
if __name__ == '__main__':
ssh = SSHLib(
manufacturer='h3c', ssh_ip='xxx.xxx.xxx.xxx', ssh_port=22,
ssh_username='xxx', ssh_password='xxx'
)
speed = ssh.get_cir(port='xxx')
print(speed)
status = ssh.set_cir(behavior=speed.get('behavior'), cir=20000)
print(status)
speed = ssh.get_cir(port='xxx')
print(speed)
print(ssh.logs)