Paramiko to Cisco IOS router

Rewrite this using netmiko!


In [1]:
import paramiko.client

In [2]:
client = paramiko.client.SSHClient()

In [3]:
client.set_missing_host_key_policy(paramiko.client.AutoAddPolicy())

In [4]:
client.connect('10.1.1.26', username='cisco', password='cisco', port=22, timeout=10, look_for_keys=False, allow_agent=False)

In [5]:
shell = client.invoke_shell()

In [6]:
if shell.recv_ready():
    out = shell.recv(65535)
    print (out)


b'\r\nrouter1>'

In [7]:
shell.send('enable\n')


Out[7]:
7

In [8]:
if shell.recv_ready():
    out = shell.recv(65535)
    print (out)


b'enable\r\nPassword: '

In [9]:
shell.send('enable\n')


Out[9]:
7

In [10]:
if shell.recv_ready():
    out = shell.recv(65535)
    print (out)


b'\r\nrouter1#'

In [11]:
shell.send('terminal length 0\n')


Out[11]:
18

In [12]:
if shell.recv_ready():
    out = shell.recv(65535)
    print (out)


b'terminal length 0\r\nrouter1#'

In [13]:
shell.send('conf t\n')


Out[13]:
7

In [14]:
if shell.recv_ready():
    out = shell.recv(65535)
    print (out)


b'conf t\r\nEnter configuration commands, one per line.  End with CNTL/Z.\r\nrouter1(config)#'

In [15]:
shell.send('?')


Out[15]:
1

In [16]:
if shell.recv_ready():
    out = shell.recv(65535)
    print (out)


b"?\r\nConfigure commands:\r\n  aaa                         Authentication, Authorization and Accounting.\r\n  access-list                 Add an access list entry\r\n  access-session              Access Session Global Configuration Commands\r\n  alarm                       Configure alarm profile\r\n  alias                       Create command alias\r\n  archive                     Archive the configuration\r\n  arp                         Set a static ARP entry\r\n  authentication              Auth Manager Global Configuration Commands\r\n  auto                        Configure Automation\r\n  banner                      Define a login banner\r\n  beep                        Configure BEEP (Blocks Extensible Exchange\r\n                              Protocol)\r\n  boot                        Modify system boot parameters\r\n  bridge                      Bridge Group.\r\n  buffers                     Adjust system buffer pool parameters\r\n  call-home                   Enter call-home configuration mode\r\n  cdp                         Global CDP configuration subcommands\r\n  cef                         Cisco Express Forwarding\r\n  cip                         CIP protocol\r\n  cisp                        Set CISP parameters\r\n  class-map                   Configure CPL Class Map\r\n  clns                        Global CLNS configuration subcommands\r\n  clock                       Configure time-of-day clock\r\n  cluster                     Cluster configuration commands\r\n  cns                         CNS agents\r\n  crypto                      Encryption module\r\n  default                     Set a command to its defaults\r\n  default-value               Default character-bits values\r\n  define                      interface range macro definition\r\n  diagnostic                  Configure diagnostic information\r\n  dnsix-dmdp                  Provide DMDP service for DNSIX\r\n  dnsix-nat                   Provide DNSIX service for audit trails\r\n  do-exec                     To run exec commands in config mode\r\n  dot1x                       IEEE 802.1X Global Configuration Commands\r\n  downward-compatible-config  Generate a configuration compatible with older\r\n                              software\r\n  eap                         EAP Global Configuration Commands\r\n  emm                         Specify pre-loading of MDF\r\n  enable                      Modify enable password parameters\r\n  end                         Exit from configure mode\r\n  eou                         EAPoUDP Global Configuration Commands\r\n  epm                         EPM Global Configuration Commands\r\n  errdisable                  Error disable\r\n  event                       Event related configuration commands\r\n  exception                   Exception handling\r\n  exit                        Exit from configure mode\r\n  fallback                    Fallback configuration commands\r\n  file                        Adjust file system parameters\r\n  format                      Format the output\r\n  global-address-family       Enter address-family base routing topology mode\r\n  help                        Description of the interactive help system\r\n  hostname                    Set system's network name\r\n  hw-module                   Control of individual components in the system\r\n  identity                    Identity Configuration Commands\r\n  interface                   Select an interface to configure\r\n  ip                          Global IP configuration subcommands\r\n  ipc                         Configure IPC system\r\n  isis                        Global ISIS configuration subcommands\r\n  ixi                         IXI Config command\r\n  kerberos                    Configure Kerberos\r\n  key                         Key management\r\n  kron                        Kron interval Facility\r\n  l2protocol-tunnel           Tunnel Layer2 protocols\r\n  lacp                        LACP configuration\r\n  ldap                        LDAP configuration commands\r\n  li-view                     LI View\r\n  line                        Configure a terminal line\r\n  link                        Enable Link State Tracking feature\r\n  lldp                        Global LLDP configuration subcommands\r\n  location                    Global location configuration commands\r\n  logging                     Modify message logging facilities\r\n  login                       Enable secure login checking\r\n  mab                         MAC Authentication Bypass Global Configuration\r\n                              Commands\r\n  mac                         Global MAC configuration subcommands\r\n  macro                       Macro configuration\r\n  map-class                   Configure static map class\r\n  map-list                    Configure static map list\r\n  memory                      Configure memory management\r\n  mls                         mls global commands\r\n  monitor                     Monitoring different system events\r\n  mvr                         Enable/Disable MVR on the switch\r\n  netconf                     Configure NETCONF\r\n  network-policy              Network Policy\r\n  nmsp                        NMSP configuration commands\r\n  no                          Negate a command or set its defaults\r\n  ntp                         Configure NTP\r\n  parser                      Configure parser\r\n  password                    Configure encryption password (key)\r\n  platform                    platform specific config commands\r\n  policy-manager              Policy Manager configuration commands\r\n  policy-map                  Configure CPL Policy Map\r\n  port-channel                EtherChannel configuration\r\n  power                       Power configure\r\n  power-supply                Set the system power supply settings\r\n  priority-list               Build a priority list\r\n  privilege                   Command privilege parameters\r\n  process                     Configure process\r\n  process-max-time            Maximum time for process to run before\r\n                              voluntarily relinquishing processor\r\n  profinet                    profinet protocol\r\n  psp                         Enable PSP\r\n  ptp                         Global PTP configuration commands\r\n  qos                         Global QoS configuration subcommands\r\n  queue-list                  Build a custom queue list\r\n  radius                      RADIUS server configuration command\r\n  radius-server               Modify RADIUS query parameters\r\n  regexp                      regexp commands\r\n  rep                         Resilient Ethernet Protocol characteristics\r\n  resource                    Configure Resource settings\r\n  rmon                        Remote Monitoring\r\n  route-map                   Create route-map or enter route-map command mode\r\n  router                      Enable a routing process\r\n  sasl                        Configure SASL\r\n  scheduler                   Scheduler parameters\r\n  scripting                   Configure options for scripting languages\r\n  sdm                         Switch database management\r\n  service                     Modify use of network based services\r\n  service-family              Configure extenal service-family clients\r\n  setup                       Configure setup options\r\n  shell                       Configure shell command\r\n  shutdown                    Shutdown system elements\r\n  snmp                        Modify non engine SNMP parameters\r\n  snmp-server                 Modify SNMP engine parameters\r\n  spanning-tree               Spanning Tree Subsystem\r\n  stackmaker                  Specify stack name and add its member\r\n  stacks                      Configure stacks\r\n  standby                     Global HSRP configuration commands\r\n  subscriber-policy           Subscriber policy\r\n  system                      Set the system configuration\r\n  table-map                   Configure Table Map\r\n  tacacs                      TACACS server configuration command\r\n  tacacs-server               Modify TACACS query parameters\r\n  template                    Select a template to configure\r\n  tftp-server                 Provide TFTP service for netload requests\r\n  time-range                  Define time range entries\r\n  track                       Object tracking configuration commands\r\n  udld                        Configure global UDLD setting\r\n  username                    Establish User Name Authentication\r\n  vlan                        Vlan commands\r\n  vmps                        VMPS settings\r\n  vrf                         VRF commands\r\n  vtp                         Configure global VTP state\r\n  wsma                        Configure Web Services Management Agents\r\n  xdr                         Configure XDR parameters\r\n\r\nrouter1(config)#"

In [17]:
str(out).split('\\r\\n')


Out[17]:
['b"?',
 'Configure commands:',
 '  aaa                         Authentication, Authorization and Accounting.',
 '  access-list                 Add an access list entry',
 '  access-session              Access Session Global Configuration Commands',
 '  alarm                       Configure alarm profile',
 '  alias                       Create command alias',
 '  archive                     Archive the configuration',
 '  arp                         Set a static ARP entry',
 '  authentication              Auth Manager Global Configuration Commands',
 '  auto                        Configure Automation',
 '  banner                      Define a login banner',
 '  beep                        Configure BEEP (Blocks Extensible Exchange',
 '                              Protocol)',
 '  boot                        Modify system boot parameters',
 '  bridge                      Bridge Group.',
 '  buffers                     Adjust system buffer pool parameters',
 '  call-home                   Enter call-home configuration mode',
 '  cdp                         Global CDP configuration subcommands',
 '  cef                         Cisco Express Forwarding',
 '  cip                         CIP protocol',
 '  cisp                        Set CISP parameters',
 '  class-map                   Configure CPL Class Map',
 '  clns                        Global CLNS configuration subcommands',
 '  clock                       Configure time-of-day clock',
 '  cluster                     Cluster configuration commands',
 '  cns                         CNS agents',
 '  crypto                      Encryption module',
 '  default                     Set a command to its defaults',
 '  default-value               Default character-bits values',
 '  define                      interface range macro definition',
 '  diagnostic                  Configure diagnostic information',
 '  dnsix-dmdp                  Provide DMDP service for DNSIX',
 '  dnsix-nat                   Provide DNSIX service for audit trails',
 '  do-exec                     To run exec commands in config mode',
 '  dot1x                       IEEE 802.1X Global Configuration Commands',
 '  downward-compatible-config  Generate a configuration compatible with older',
 '                              software',
 '  eap                         EAP Global Configuration Commands',
 '  emm                         Specify pre-loading of MDF',
 '  enable                      Modify enable password parameters',
 '  end                         Exit from configure mode',
 '  eou                         EAPoUDP Global Configuration Commands',
 '  epm                         EPM Global Configuration Commands',
 '  errdisable                  Error disable',
 '  event                       Event related configuration commands',
 '  exception                   Exception handling',
 '  exit                        Exit from configure mode',
 '  fallback                    Fallback configuration commands',
 '  file                        Adjust file system parameters',
 '  format                      Format the output',
 '  global-address-family       Enter address-family base routing topology mode',
 '  help                        Description of the interactive help system',
 "  hostname                    Set system's network name",
 '  hw-module                   Control of individual components in the system',
 '  identity                    Identity Configuration Commands',
 '  interface                   Select an interface to configure',
 '  ip                          Global IP configuration subcommands',
 '  ipc                         Configure IPC system',
 '  isis                        Global ISIS configuration subcommands',
 '  ixi                         IXI Config command',
 '  kerberos                    Configure Kerberos',
 '  key                         Key management',
 '  kron                        Kron interval Facility',
 '  l2protocol-tunnel           Tunnel Layer2 protocols',
 '  lacp                        LACP configuration',
 '  ldap                        LDAP configuration commands',
 '  li-view                     LI View',
 '  line                        Configure a terminal line',
 '  link                        Enable Link State Tracking feature',
 '  lldp                        Global LLDP configuration subcommands',
 '  location                    Global location configuration commands',
 '  logging                     Modify message logging facilities',
 '  login                       Enable secure login checking',
 '  mab                         MAC Authentication Bypass Global Configuration',
 '                              Commands',
 '  mac                         Global MAC configuration subcommands',
 '  macro                       Macro configuration',
 '  map-class                   Configure static map class',
 '  map-list                    Configure static map list',
 '  memory                      Configure memory management',
 '  mls                         mls global commands',
 '  monitor                     Monitoring different system events',
 '  mvr                         Enable/Disable MVR on the switch',
 '  netconf                     Configure NETCONF',
 '  network-policy              Network Policy',
 '  nmsp                        NMSP configuration commands',
 '  no                          Negate a command or set its defaults',
 '  ntp                         Configure NTP',
 '  parser                      Configure parser',
 '  password                    Configure encryption password (key)',
 '  platform                    platform specific config commands',
 '  policy-manager              Policy Manager configuration commands',
 '  policy-map                  Configure CPL Policy Map',
 '  port-channel                EtherChannel configuration',
 '  power                       Power configure',
 '  power-supply                Set the system power supply settings',
 '  priority-list               Build a priority list',
 '  privilege                   Command privilege parameters',
 '  process                     Configure process',
 '  process-max-time            Maximum time for process to run before',
 '                              voluntarily relinquishing processor',
 '  profinet                    profinet protocol',
 '  psp                         Enable PSP',
 '  ptp                         Global PTP configuration commands',
 '  qos                         Global QoS configuration subcommands',
 '  queue-list                  Build a custom queue list',
 '  radius                      RADIUS server configuration command',
 '  radius-server               Modify RADIUS query parameters',
 '  regexp                      regexp commands',
 '  rep                         Resilient Ethernet Protocol characteristics',
 '  resource                    Configure Resource settings',
 '  rmon                        Remote Monitoring',
 '  route-map                   Create route-map or enter route-map command mode',
 '  router                      Enable a routing process',
 '  sasl                        Configure SASL',
 '  scheduler                   Scheduler parameters',
 '  scripting                   Configure options for scripting languages',
 '  sdm                         Switch database management',
 '  service                     Modify use of network based services',
 '  service-family              Configure extenal service-family clients',
 '  setup                       Configure setup options',
 '  shell                       Configure shell command',
 '  shutdown                    Shutdown system elements',
 '  snmp                        Modify non engine SNMP parameters',
 '  snmp-server                 Modify SNMP engine parameters',
 '  spanning-tree               Spanning Tree Subsystem',
 '  stackmaker                  Specify stack name and add its member',
 '  stacks                      Configure stacks',
 '  standby                     Global HSRP configuration commands',
 '  subscriber-policy           Subscriber policy',
 '  system                      Set the system configuration',
 '  table-map                   Configure Table Map',
 '  tacacs                      TACACS server configuration command',
 '  tacacs-server               Modify TACACS query parameters',
 '  template                    Select a template to configure',
 '  tftp-server                 Provide TFTP service for netload requests',
 '  time-range                  Define time range entries',
 '  track                       Object tracking configuration commands',
 '  udld                        Configure global UDLD setting',
 '  username                    Establish User Name Authentication',
 '  vlan                        Vlan commands',
 '  vmps                        VMPS settings',
 '  vrf                         VRF commands',
 '  vtp                         Configure global VTP state',
 '  wsma                        Configure Web Services Management Agents',
 '  xdr                         Configure XDR parameters',
 '',
 'router1(config)#"']

In [18]:
shell.send('aa\t')


Out[18]:
3

In [19]:
if shell.recv_ready():
    out = shell.recv(65535)
    print (out)


b'aa\r\nrouter1(config)#aaa '

In [20]:
shell.send('aaa ?')


Out[20]:
5

In [21]:
if shell.recv_ready():
    out = shell.recv(65535)
    print (out)


b'aaa ?\r\n% Unrecognized command\r\nrouter1(config)#aaa aaa '

In [22]:
CTRLC = '\x03' ; shell.send(CTRLC)


Out[22]:
1

In [23]:
if shell.recv_ready():
    out = shell.recv(65535)
    print (out)


b'\r\nrouter1#'

In [24]:
shell.send('conf t\n')


Out[24]:
7

In [25]:
if shell.recv_ready():
    out = shell.recv(65535)
    print (out)


b'conf t\r\nEnter configuration commands, one per line.  End with CNTL/Z.\r\nrouter1(config)#'

In [26]:
shell.send('aaa ')


Out[26]:
4

In [27]:
if shell.recv_ready():
    out = shell.recv(65535)
    print (out)


b'aaa '

In [28]:
shell.send('?')


Out[28]:
1

In [29]:
if shell.recv_ready():
    out = shell.recv(65535)
    print (out)


b'?\r\n  accounting       Accounting configurations parameters.\r\n  attribute        AAA attribute definitions\r\n  authentication   Authentication configurations parameters.\r\n  authorization    Authorization configurations parameters.\r\n  cache            AAA cache definitions\r\n  configuration    Authorization configuration parameters.\r\n  dnis             Associate certain AAA parameters to a specific DNIS number\r\n  group            AAA group definitions\r\n  local            AAA Local method options\r\n  max-sessions     Adjust initial hash size for estimated max sessions\r\n  memory           AAA memory parameters\r\n  nas              NAS specific configuration\r\n  new-model        Enable NEW access control commands and functions.(Disables\r\n                   OLD commands.)\r\n  password         Configure password/secret related settings\r\n  pod              POD processing\r\n  policy           AAA policy parameters\r\n  server           Local AAA server\r\n  service-profile  Service-Profile parameters\r\n  session-id       AAA Session ID\r\n  traceback        Traceback recording\r\n  user             AAA user definitions\r\n\r\nrouter1(config)#aaa '

In [30]:
str(out).split('\\r\\n')


Out[30]:
["b'?",
 '  accounting       Accounting configurations parameters.',
 '  attribute        AAA attribute definitions',
 '  authentication   Authentication configurations parameters.',
 '  authorization    Authorization configurations parameters.',
 '  cache            AAA cache definitions',
 '  configuration    Authorization configuration parameters.',
 '  dnis             Associate certain AAA parameters to a specific DNIS number',
 '  group            AAA group definitions',
 '  local            AAA Local method options',
 '  max-sessions     Adjust initial hash size for estimated max sessions',
 '  memory           AAA memory parameters',
 '  nas              NAS specific configuration',
 '  new-model        Enable NEW access control commands and functions.(Disables',
 '                   OLD commands.)',
 '  password         Configure password/secret related settings',
 '  pod              POD processing',
 '  policy           AAA policy parameters',
 '  server           Local AAA server',
 '  service-profile  Service-Profile parameters',
 '  session-id       AAA Session ID',
 '  traceback        Traceback recording',
 '  user             AAA user definitions',
 '',
 "router1(config)#aaa '"]

In [31]:
import re
[re.split('[\s]+',s[2:])[0] for s in str(out).split('\\r\\n') if len(s) > 2 and s[2] != ' ' and s[0] == ' ']


Out[31]:
['accounting',
 'attribute',
 'authentication',
 'authorization',
 'cache',
 'configuration',
 'dnis',
 'group',
 'local',
 'max-sessions',
 'memory',
 'nas',
 'new-model',
 'password',
 'pod',
 'policy',
 'server',
 'service-profile',
 'session-id',
 'traceback',
 'user']

In [32]:
shell.send('authentication')


Out[32]:
14

In [33]:
if shell.recv_ready():
    out = shell.recv(65535)
    print (out)


b'authentication'

In [34]:
shell.send(' ?')


Out[34]:
2

In [35]:
if shell.recv_ready():
    out = shell.recv(65535)
    print (out)


b' ?\r\n  arap             Set authentication lists for arap.\r\n  attempts         Set the maximum number of authentication attempts\r\n  banner           Message to use when starting login/authentication.\r\n  dot1x            Set authentication lists for IEEE 802.1x.\r\n  enable           Set authentication list for enable.\r\n  eou              Set authentication lists for EAPoUDP\r\n  fail-message     Message to use for failed login/authentication.\r\n  login            Set authentication lists for logins.\r\n  password-prompt  Text to use when prompting for a password\r\n  ppp              Set authentication lists for ppp.\r\n  sgbp             Set authentication lists for sgbp.\r\n  suppress         Do not send access request for a specific type of user.\r\n  username-prompt  Text to use when prompting for a username\r\n\r\nrouter1(config)#aaa authentication '

In [36]:
[re.split('[\s]+',s[2:])[0] for s in str(out).split('\\r\\n') if len(s) > 2 and s[2] != ' ' and s[0] == ' ']


Out[36]:
['arap',
 'attempts',
 'banner',
 'dot1x',
 'enable',
 'eou',
 'fail-message',
 'login',
 'password-prompt',
 'ppp',
 'sgbp',
 'suppress',
 'username-prompt']

In [37]:
shell.send(CTRLC)
shell.send('conf t\n')


Out[37]:
7

In [38]:
if shell.recv_ready():
    out = shell.recv(65535)
    print (out)


b'\r\nrouter1#conf t\r\nEnter configuration commands, one per line.  End with CNTL/Z.\r\nrouter1(config)#'

In [39]:
shell.send('aaa authentication')


Out[39]:
18

In [40]:
shell.send(' ?')


Out[40]:
2

In [41]:
if shell.recv_ready():
    out = shell.recv(65535)
    print (out)


b'aaa authentication ?\r\n  arap             Set authentication lists for arap.\r\n  attempts         Set the maximum number of authentication attempts\r\n  banner           Message to use when starting login/authentication.\r\n  dot1x            Set authentication lists for IEEE 802.1x.\r\n  enable           Set authentication list for enable.\r\n  eou              Set authentication lists for EAPoUDP\r\n  fail-message     Message to use for failed login/authentication.\r\n  login            Set authentication lists for logins.\r\n  password-prompt  Text to use when prompting for a password\r\n  ppp              Set authentication lists for ppp.\r\n  sgbp             Set authentication lists for sgbp.\r\n  suppress         Do not send access request for a specific type of user.\r\n  username-prompt  Text to use when prompting for a username\r\n\r\nrouter1(config)#aaa authentication '

In [42]:
[re.split('[\s]+',s[2:])[0] for s in str(out).split('\\r\\n') if len(s) > 2 and s[2] != ' ' and s[0] == ' ']


Out[42]:
['arap',
 'attempts',
 'banner',
 'dot1x',
 'enable',
 'eou',
 'fail-message',
 'login',
 'password-prompt',
 'ppp',
 'sgbp',
 'suppress',
 'username-prompt']

In [ ]: