Skip to content

Commit

Permalink
chapter 27 examples
Browse files Browse the repository at this point in the history
  • Loading branch information
natenka committed Aug 17, 2019
1 parent 117f805 commit c794469
Show file tree
Hide file tree
Showing 3 changed files with 94 additions and 0 deletions.
31 changes: 31 additions & 0 deletions examples/27_oop_inheritance/cisco_ssh_class.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
from connect_ssh_class import ConnectSSH
import time


class CiscoSSH(ConnectSSH):
def __init__(self, ip, username, password, enable_password,
disable_paging=True):
super().__init__(ip, username, password)
self._ssh.send('enable\n')
self._ssh.send(enable_password +'\n')
if disable_paging:
self._ssh.send('terminal length 0\n')
time.sleep(1)
self._ssh.recv(self._MAX_READ)

def config_mode(self):
self._ssh.send('conf t\n')
time.sleep(0.2)
result = self._ssh.recv(self._MAX_READ).decode('ascii')
return result

def exit_config_mode(self):
return super().send_command('end')

def send_config_commands(self, commands):
output = self.config_mode()
output += super().send_config_commands(commands)
output += self.exit_config_mode()
return output


48 changes: 48 additions & 0 deletions examples/27_oop_inheritance/connect_ssh_class.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import paramiko
import time


class ConnectSSH:
def __init__(self, ip, username, password):
self.ip = ip
self.username = username
self.password = password
self._MAX_READ = 10000

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

client.connect(
hostname=ip,
username=username,
password=password,
look_for_keys=False,
allow_agent=False)

self._ssh = client.invoke_shell()
time.sleep(1)
self._ssh.recv(self._MAX_READ)

def send_command(self, command):
self._ssh.send(command + '\n')
time.sleep(2)
result = self._ssh.recv(self._MAX_READ).decode('ascii')
return result

def send_config_commands(self, commands):
if isinstance(commands, str):
commands = [commands]
for command in commands:
self._ssh.send(command + '\n')
time.sleep(0.5)
result = self._ssh.recv(self._MAX_READ).decode('ascii')
return result

def __enter__(self):
return self

def __exit__(self, exc_type, exc_value, traceback):
self._ssh.close()

def close(self):
self._ssh.close()
15 changes: 15 additions & 0 deletions examples/27_oop_inheritance/netmiko_inheritance.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
from netmiko.cisco.cisco_ios import CiscoIosSSH


class ErrorInCommand(Exception):
"""Это исключение генерируется при ошибке в команде"""


class MyNetmiko(CiscoIosSSH):
def send_command(self, command, **kwargs):
output = super().send_command(command, **kwargs)
if 'Invalid input' in output:
raise ErrorInCommand('Возникла ошибка')
return output


0 comments on commit c794469

Please sign in to comment.