SHOW:
|
|
- or go back to the newest paste.
| 1 | #!/usr/bin/env python | |
| 2 | ||
| 3 | from netmiko import ConnectHandler | |
| 4 | import getpass | |
| 5 | import textwrap | |
| 6 | import getpass | |
| 7 | from os.path import expanduser | |
| 8 | ||
| 9 | ||
| 10 | class CiscoIOS: | |
| 11 | ||
| 12 | def __init__(self, device_param): | |
| 13 | self.device_param = device_param | |
| 14 | self.ssh = ConnectHandler(**device_param) | |
| 15 | ||
| 16 | def load_ssh_key(self, id_rsa=None, user=None): | |
| 17 | if not id_rsa: | |
| 18 | id_rsa = expanduser('~') + '/.ssh/id_rsa.pub'
| |
| 19 | if not user: | |
| 20 | user = getpass.getuser() | |
| 21 | pubkey = open(id_rsa, 'r').read() | |
| 22 | pubkey = textwrap.wrap(pubkey, 80) | |
| 23 | ||
| 24 | commands = ['ip ssh pubkey-chain', | |
| 25 | 'username ' + user, | |
| 26 | 'key-string'] + pubkey + ['exit'] | |
| 27 | ||
| 28 | return self.ssh.send_config_set(commands) | |
| 29 | ||
| 30 | def del_ssh_key(self, user): | |
| 31 | commands = ['ip ssh pubkey-chain', | |
| 32 | 'no username ' + user, | |
| 33 | 'exit'] | |
| 34 | return self.ssh.send_config_set(commands) | |
| 35 | ||
| 36 | def write_memory(self): | |
| 37 | ret = 'enable password is not set' | |
| 38 | if not self.ssh.check_enable_mode() and \ | |
| 39 | self.device_param['secret']: | |
| 40 | self.ssh.enable() | |
| 41 | ret = self.ssh.send_command('write memory')
| |
| 42 | self.ssh.exit_enable_mode() | |
| 43 | return ret | |
| 44 | ||
| 45 | if __name__ == '__main__': | |
| 46 | pwd = getpass.getpass() | |
| 47 | device = {'device_type': 'cisco_ios',
| |
| 48 | 'ip': 'acc-sw-1', | |
| 49 | 'username': 'anon', | |
| 50 | 'password': pwd, | |
| 51 | 'secret': ''} | |
| 52 | cisco = CiscoIOS(device) | |
| 53 | print(cisco.load_ssh_key(user='anon')) | |
| 54 | print(cisco.write_memory()) |