<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/"><channel><title>Netmiko · Network Doodles</title><link>https://networkdoodles.com/tags/netmiko/</link><description>Network automation, from first playbook to agentic operations. Ansible, NetBox, MCP, Python and the occasional doodle.</description><language>en-us</language><managingEditor>David Henderson</managingEditor><lastBuildDate>Mon, 16 Nov 2026 09:00:00 -0500</lastBuildDate><atom:link href="https://networkdoodles.com/tags/netmiko/index.xml" rel="self" type="application/rss+xml"/><item><title>Capstone: an Inventory to CSV (Python 101, Lesson 8)</title><link>https://networkdoodles.com/lessons/python-101/inventory-to-csv/</link><pubDate>Mon, 16 Nov 2026 09:00:00 -0500</pubDate><dc:creator>David Henderson</dc:creator><guid>https://networkdoodles.com/lessons/python-101/inventory-to-csv/</guid><category>python</category><category>network-automation</category><category>howto</category><category>capeos</category><category>netmiko</category><description>Build a small network tool in Python: inventory in, Netmiko and TextFSM per device, csv.DictWriter out, carry on past failed devices, exit codes and argparse.</description><content:encoded xmlns:content="http://purl.org/rss/1.0/modules/content/"><![CDATA[<p>A useful network script has the same shape whatever it does: it reads an inventory, does one job per device,
and writes the results where a person or another tool can use them. Give each step its own function, catch
failures <strong>per device</strong> so one dead router doesn&rsquo;t stop the rest, and finish with an <strong>exit code</strong> that says
whether everything worked. The capstone puts that shape around lessons 2 to 7, and ends with a CSV of every
device&rsquo;s version and serial number.</p>
<p>The tool is <code>scripts/inventory.py</code> in the <a href="/labs/python-101/">lab</a>. This lesson walks through the decisions in
it: three small functions instead of one long script, two device types&rsquo; <code>show version</code> in one row,
<code>csv.DictWriter</code>, what happens when r2 is switched off, and two options with <code>argparse</code>. Every output below is
from the lab: Python 3.11, Netmiko 4.8 and ntc-templates 9.3, against CapeOS.</p>
<hr>
<h2 id="what-shape-should-a-small-network-tool-have">What shape should a small network tool have?</h2>
<p>Inventory in, one function per step, results out. This is the script&rsquo;s <code>main()</code>:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">main</span><span class="p">(</span><span class="n">argv</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="n">args</span> <span class="o">=</span> <span class="n">parse_args</span><span class="p">(</span><span class="n">argv</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="n">devices</span> <span class="o">=</span> <span class="n">load_devices</span><span class="p">(</span><span class="n">args</span><span class="o">.</span><span class="n">source</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="n">rows</span><span class="p">,</span> <span class="n">failures</span> <span class="o">=</span> <span class="n">run</span><span class="p">(</span><span class="n">devices</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="n">write_csv</span><span class="p">(</span><span class="n">rows</span><span class="p">,</span> <span class="n">args</span><span class="o">.</span><span class="n">out</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s2">&#34;wrote </span><span class="si">{</span><span class="n">args</span><span class="o">.</span><span class="n">out</span><span class="si">}</span><span class="s2">: </span><span class="si">{</span><span class="nb">len</span><span class="p">(</span><span class="n">rows</span><span class="p">)</span><span class="si">}</span><span class="s2"> of </span><span class="si">{</span><span class="nb">len</span><span class="p">(</span><span class="n">devices</span><span class="p">)</span><span class="si">}</span><span class="s2"> devices&#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="k">for</span> <span class="n">name</span><span class="p">,</span> <span class="n">reason</span> <span class="ow">in</span> <span class="n">failures</span><span class="o">.</span><span class="n">items</span><span class="p">():</span>
</span></span><span class="line"><span class="cl">        <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s2">&#34;  couldn&#39;t inventory </span><span class="si">{</span><span class="n">reason</span><span class="si">}</span><span class="s2">&#34;</span><span class="p">,</span> <span class="n">file</span><span class="o">=</span><span class="n">sys</span><span class="o">.</span><span class="n">stderr</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="mi">2</span> <span class="k">if</span> <span class="n">failures</span> <span class="k">else</span> <span class="mi">0</span>
</span></span></code></pre></div><p>It reads as a list of steps, and each step is a function in <code>netlab/report.py</code> or the script itself:</p>
<table>
  <thead>
      <tr>
          <th>Function</th>
          <th>Takes</th>
          <th>Gives back</th>
          <th>Network job</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td><code>parse_args()</code></td>
          <td>the command line</td>
          <td>which source, which file</td>
          <td>none: the tool&rsquo;s settings</td>
      </tr>
      <tr>
          <td><code>load_devices(source)</code></td>
          <td><code>&quot;yaml&quot;</code> or <code>&quot;api&quot;</code></td>
          <td>a list of device dicts</td>
          <td>read the inventory (lesson 7)</td>
      </tr>
      <tr>
          <td><code>facts(device)</code></td>
          <td>one device dict</td>
          <td>one row, as a dict</td>
          <td>log in, <code>show version</code>, <code>show ip interface brief</code></td>
      </tr>
      <tr>
          <td><code>run(devices)</code></td>
          <td>the device list</td>
          <td>the rows, and the failures</td>
          <td><code>facts()</code> for every device</td>
      </tr>
      <tr>
          <td><code>write_csv(rows, path)</code></td>
          <td>the rows, a file name</td>
          <td>nothing: it writes the file</td>
          <td>the report</td>
      </tr>
  </tbody>
</table>
<p>Why not one long script? Because a function with one job can be tried on its own. You can call <code>facts()</code> on
r3 in the REPL and look at the dict before any CSV exists, and the lab&rsquo;s checker does the same: it calls
<code>run()</code> with a device list it made up, including a device that doesn&rsquo;t exist. A script with no functions can
only be tested by running all of it against the network.</p>
<p>Each piece is also replaceable. When the inventory moves from a YAML file to an API, only <code>load_devices()</code>
changes. It&rsquo;s the same idea that makes <a href="/posts/netboxasinventory/">NetBox as your Ansible inventory</a> work: the
tool asks for devices, not for a particular file.</p>
<hr>
<h2 id="why-doesnt-show-version-give-the-same-keys-on-every-device">Why doesn&rsquo;t show version give the same keys on every device?</h2>
<p>Because ntc-templates has one template per platform and command, each written for one CLI, and each names its
fields after what that CLI prints. Here are r1 (CapeOS Bolt, which Netmiko knows as <code>cisco_ios</code>) and r3
(CapeOS Pulse, <code>arista_eos</code>), parsed with <code>parse_output()</code> from <a href="/lessons/python-101/regex-and-textfsm/">lesson 5</a>:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="o">&gt;&gt;&gt;</span> <span class="n">parse_output</span><span class="p">(</span><span class="n">platform</span><span class="o">=</span><span class="s2">&#34;cisco_ios&#34;</span><span class="p">,</span> <span class="n">command</span><span class="o">=</span><span class="s2">&#34;show version&#34;</span><span class="p">,</span> <span class="n">data</span><span class="o">=</span><span class="nb">open</span><span class="p">(</span><span class="s2">&#34;checks/data/version-r1.txt&#34;</span><span class="p">)</span><span class="o">.</span><span class="n">read</span><span class="p">())</span>
</span></span><span class="line"><span class="cl"><span class="p">[{</span><span class="s1">&#39;software_image&#39;</span><span class="p">:</span> <span class="s1">&#39;CO-BOLT&#39;</span><span class="p">,</span> <span class="s1">&#39;version&#39;</span><span class="p">:</span> <span class="s1">&#39;0.11.2&#39;</span><span class="p">,</span> <span class="s1">&#39;release&#39;</span><span class="p">:</span> <span class="s1">&#39;&#39;</span><span class="p">,</span> <span class="s1">&#39;rommon&#39;</span><span class="p">:</span> <span class="s1">&#39;&#39;</span><span class="p">,</span> <span class="s1">&#39;hostname&#39;</span><span class="p">:</span> <span class="s1">&#39;r1&#39;</span><span class="p">,</span> <span class="s1">&#39;uptime&#39;</span><span class="p">:</span> <span class="s1">&#39;0 minutes&#39;</span><span class="p">,</span> <span class="s1">&#39;uptime_years&#39;</span><span class="p">:</span> <span class="s1">&#39;&#39;</span><span class="p">,</span> <span class="s1">&#39;uptime_weeks&#39;</span><span class="p">:</span> <span class="s1">&#39;&#39;</span><span class="p">,</span> <span class="s1">&#39;uptime_days&#39;</span><span class="p">:</span> <span class="s1">&#39;&#39;</span><span class="p">,</span> <span class="s1">&#39;uptime_hours&#39;</span><span class="p">:</span> <span class="s1">&#39;&#39;</span><span class="p">,</span> <span class="s1">&#39;uptime_minutes&#39;</span><span class="p">:</span> <span class="s1">&#39;0&#39;</span><span class="p">,</span> <span class="s1">&#39;reload_reason&#39;</span><span class="p">:</span> <span class="s1">&#39;&#39;</span><span class="p">,</span> <span class="s1">&#39;running_image&#39;</span><span class="p">:</span> <span class="s1">&#39;capeos-bolt.bin&#39;</span><span class="p">,</span> <span class="s1">&#39;hardware&#39;</span><span class="p">:</span> <span class="p">[],</span> <span class="s1">&#39;serial&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s1">&#39;CAPEHFI5RPW&#39;</span><span class="p">],</span> <span class="s1">&#39;config_register&#39;</span><span class="p">:</span> <span class="s1">&#39;0x2102&#39;</span><span class="p">,</span> <span class="s1">&#39;mac_address&#39;</span><span class="p">:</span> <span class="p">[],</span> <span class="s1">&#39;restarted&#39;</span><span class="p">:</span> <span class="s1">&#39;&#39;</span><span class="p">}]</span>
</span></span><span class="line"><span class="cl"><span class="o">&gt;&gt;&gt;</span> <span class="n">parse_output</span><span class="p">(</span><span class="n">platform</span><span class="o">=</span><span class="s2">&#34;arista_eos&#34;</span><span class="p">,</span> <span class="n">command</span><span class="o">=</span><span class="s2">&#34;show version&#34;</span><span class="p">,</span> <span class="n">data</span><span class="o">=</span><span class="nb">open</span><span class="p">(</span><span class="s2">&#34;checks/data/version-r3-pulse.txt&#34;</span><span class="p">)</span><span class="o">.</span><span class="n">read</span><span class="p">())</span>
</span></span><span class="line"><span class="cl"><span class="p">[{</span><span class="s1">&#39;model&#39;</span><span class="p">:</span> <span class="s1">&#39;&#39;</span><span class="p">,</span> <span class="s1">&#39;hw_version&#39;</span><span class="p">:</span> <span class="s1">&#39;&#39;</span><span class="p">,</span> <span class="s1">&#39;serial_number&#39;</span><span class="p">:</span> <span class="s1">&#39;CAPE4S5VG44&#39;</span><span class="p">,</span> <span class="s1">&#39;sys_mac&#39;</span><span class="p">:</span> <span class="s1">&#39;cae2.b268.c68e&#39;</span><span class="p">,</span> <span class="s1">&#39;image&#39;</span><span class="p">:</span> <span class="s1">&#39;4.99.0C&#39;</span><span class="p">,</span> <span class="s1">&#39;total_memory&#39;</span><span class="p">:</span> <span class="s1">&#39;8025148&#39;</span><span class="p">,</span> <span class="s1">&#39;free_memory&#39;</span><span class="p">:</span> <span class="s1">&#39;6362980&#39;</span><span class="p">,</span> <span class="s1">&#39;uptime&#39;</span><span class="p">:</span> <span class="s1">&#39;0 minutes&#39;</span><span class="p">}]</span>
</span></span></code></pre></div><p>Line up what the CSV wants, and only one key is the same on both:</p>
<table>
  <thead>
      <tr>
          <th>CSV column</th>
          <th><code>cisco_ios</code> (r1, r2, sw1)</th>
          <th><code>arista_eos</code> (r3)</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td>version</td>
          <td><code>version</code>: <code>'0.11.2'</code></td>
          <td><code>image</code>: <code>'4.99.0C'</code></td>
      </tr>
      <tr>
          <td>serial</td>
          <td><code>serial</code>: a <strong>list</strong>, <code>['CAPEHFI5RPW']</code></td>
          <td><code>serial_number</code>: a string</td>
      </tr>
      <tr>
          <td>uptime</td>
          <td><code>uptime</code></td>
          <td><code>uptime</code></td>
      </tr>
      <tr>
          <td>hostname</td>
          <td><code>hostname</code></td>
          <td>not there</td>
      </tr>
      <tr>
          <td>model</td>
          <td><code>hardware</code>: an empty list</td>
          <td><code>model</code>: an empty string</td>
      </tr>
  </tbody>
</table>
<p>The <code>cisco_ios</code> serial is a list because a stack of switches reports one serial per member, so the template
always gives a list, even of one. And neither template finds a model on these devices: the field is there, and
empty. That&rsquo;s common. Not every device prints every fact where a template looks for it, so a tool has to
decide where each column comes from, and sometimes the answer is &ldquo;not from the device&rdquo;.</p>
<hr>
<h2 id="how-do-you-turn-two-device-types-into-one-row">How do you turn two device types into one row?</h2>
<p>Pick one name for each column, and map each device type&rsquo;s keys onto it in one place. This is the heart of
<code>facts()</code>:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl">    <span class="k">if</span> <span class="n">device</span><span class="p">[</span><span class="s2">&#34;device_type&#34;</span><span class="p">]</span> <span class="o">==</span> <span class="s2">&#34;arista_eos&#34;</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="n">release</span><span class="p">,</span> <span class="n">serial</span> <span class="o">=</span> <span class="n">version</span><span class="p">[</span><span class="s2">&#34;image&#34;</span><span class="p">],</span> <span class="n">version</span><span class="p">[</span><span class="s2">&#34;serial_number&#34;</span><span class="p">]</span>
</span></span><span class="line"><span class="cl">    <span class="k">else</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="n">release</span><span class="p">,</span> <span class="n">serial</span> <span class="o">=</span> <span class="n">version</span><span class="p">[</span><span class="s2">&#34;version&#34;</span><span class="p">],</span> <span class="n">version</span><span class="p">[</span><span class="s2">&#34;serial&#34;</span><span class="p">][</span><span class="mi">0</span><span class="p">]</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">        <span class="s2">&#34;hostname&#34;</span><span class="p">:</span> <span class="n">hostname</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">        <span class="s2">&#34;model&#34;</span><span class="p">:</span> <span class="n">device</span><span class="p">[</span><span class="s2">&#34;model&#34;</span><span class="p">],</span>
</span></span><span class="line"><span class="cl">        <span class="s2">&#34;version&#34;</span><span class="p">:</span> <span class="n">release</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">        <span class="s2">&#34;serial&#34;</span><span class="p">:</span> <span class="n">serial</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">        <span class="s2">&#34;uptime&#34;</span><span class="p">:</span> <span class="n">version</span><span class="p">[</span><span class="s2">&#34;uptime&#34;</span><span class="p">],</span>
</span></span><span class="line"><span class="cl">        <span class="s2">&#34;ip_interfaces&#34;</span><span class="p">:</span> <span class="nb">sum</span><span class="p">(</span><span class="mi">1</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">brief</span> <span class="k">if</span> <span class="n">i</span><span class="p">[</span><span class="s2">&#34;ip_address&#34;</span><span class="p">]</span> <span class="o">!=</span> <span class="s2">&#34;unassigned&#34;</span><span class="p">),</span>
</span></span><span class="line"><span class="cl">    <span class="p">}</span>
</span></span></code></pre></div><p>This is <strong>normalizing</strong>: turning data that means the same thing, spelled differently, into one shape. The <code>if</code> is
on <code>device_type</code>, the inventory field that told Netmiko which CLI to expect in
<a href="/lessons/python-101/netmiko/">lesson 6</a>. The other columns come from wherever they&rsquo;re reliable:</p>
<ul>
<li><strong>hostname</strong> is <code>conn.base_prompt</code>, which Netmiko works out from the prompt when it logs in: <code>r1#</code> gives
<code>'r1'</code>. Every device has a prompt; only one template has a <code>hostname</code> key.</li>
<li><strong>model</strong> is <code>device[&quot;model&quot;]</code>, from the inventory, because <code>show version</code> doesn&rsquo;t report one here. The
inventory is where you&rsquo;d record it anyway: it&rsquo;s what you bought.</li>
<li><strong>ip_interfaces</strong> counts the rows of <code>show ip interface brief</code> whose address isn&rsquo;t <code>unassigned</code>. Both
templates call that field <code>ip_address</code>, though Pulse&rsquo;s includes the prefix (<code>10.0.13.2/30</code>).</li>
</ul>
<p>The result, for one device of each type:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="o">&gt;&gt;&gt;</span> <span class="n">facts</span><span class="p">(</span><span class="n">devices</span><span class="p">[</span><span class="mi">0</span><span class="p">])</span>
</span></span><span class="line"><span class="cl"><span class="p">{</span><span class="s1">&#39;hostname&#39;</span><span class="p">:</span> <span class="s1">&#39;r1&#39;</span><span class="p">,</span> <span class="s1">&#39;model&#39;</span><span class="p">:</span> <span class="s1">&#39;CapeOS-Bolt&#39;</span><span class="p">,</span> <span class="s1">&#39;version&#39;</span><span class="p">:</span> <span class="s1">&#39;0.11.2&#39;</span><span class="p">,</span> <span class="s1">&#39;serial&#39;</span><span class="p">:</span> <span class="s1">&#39;CAPEHFI5RPW&#39;</span><span class="p">,</span> <span class="s1">&#39;uptime&#39;</span><span class="p">:</span> <span class="s1">&#39;10 minutes&#39;</span><span class="p">,</span> <span class="s1">&#39;ip_interfaces&#39;</span><span class="p">:</span> <span class="mi">5</span><span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="o">&gt;&gt;&gt;</span> <span class="n">facts</span><span class="p">(</span><span class="n">devices</span><span class="p">[</span><span class="mi">2</span><span class="p">])</span>
</span></span><span class="line"><span class="cl"><span class="p">{</span><span class="s1">&#39;hostname&#39;</span><span class="p">:</span> <span class="s1">&#39;r3&#39;</span><span class="p">,</span> <span class="s1">&#39;model&#39;</span><span class="p">:</span> <span class="s1">&#39;CapeOS-Pulse&#39;</span><span class="p">,</span> <span class="s1">&#39;version&#39;</span><span class="p">:</span> <span class="s1">&#39;4.99.0C&#39;</span><span class="p">,</span> <span class="s1">&#39;serial&#39;</span><span class="p">:</span> <span class="s1">&#39;CAPE4S5VG44&#39;</span><span class="p">,</span> <span class="s1">&#39;uptime&#39;</span><span class="p">:</span> <span class="s1">&#39;10 minutes&#39;</span><span class="p">,</span> <span class="s1">&#39;ip_interfaces&#39;</span><span class="p">:</span> <span class="mi">4</span><span class="p">}</span>
</span></span></code></pre></div><p>Same keys, same order, two CLIs. Everything after <code>facts()</code> can treat every device alike.</p>
<hr>
<h2 id="how-does-csvdictwriter-write-the-rows">How does csv.DictWriter write the rows?</h2>
<p><strong>CSV</strong>, comma-separated values, is a text file with one record per line and commas between the fields; any
spreadsheet opens it. <a href="/lessons/python-101/files-and-errors/">Lesson 4</a> used the <code>csv</code> module&rsquo;s plain writer,
which takes each row as a list. <code>csv.DictWriter</code> takes each row as a <strong>dict</strong>, which is what <code>facts()</code> returns,
and puts each value in its column by key:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="o">&gt;&gt;&gt;</span> <span class="n">w</span> <span class="o">=</span> <span class="n">csv</span><span class="o">.</span><span class="n">DictWriter</span><span class="p">(</span><span class="n">buf</span><span class="p">,</span> <span class="n">fieldnames</span><span class="o">=</span><span class="n">COLUMNS</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="o">&gt;&gt;&gt;</span> <span class="n">w</span><span class="o">.</span><span class="n">writeheader</span><span class="p">()</span>
</span></span><span class="line"><span class="cl"><span class="mi">52</span>
</span></span><span class="line"><span class="cl"><span class="o">&gt;&gt;&gt;</span> <span class="n">w</span><span class="o">.</span><span class="n">writerow</span><span class="p">(</span><span class="n">facts</span><span class="p">(</span><span class="n">devices</span><span class="p">[</span><span class="mi">2</span><span class="p">]))</span>
</span></span><span class="line"><span class="cl"><span class="mi">50</span>
</span></span><span class="line"><span class="cl"><span class="o">&gt;&gt;&gt;</span> <span class="n">w</span><span class="o">.</span><span class="n">writerow</span><span class="p">({</span><span class="s2">&#34;hostname&#34;</span><span class="p">:</span> <span class="s2">&#34;r9&#34;</span><span class="p">})</span>
</span></span><span class="line"><span class="cl"><span class="mi">9</span>
</span></span><span class="line"><span class="cl"><span class="o">&gt;&gt;&gt;</span> <span class="nb">print</span><span class="p">(</span><span class="n">buf</span><span class="o">.</span><span class="n">getvalue</span><span class="p">())</span>
</span></span><span class="line"><span class="cl"><span class="n">hostname</span><span class="p">,</span><span class="n">model</span><span class="p">,</span><span class="n">version</span><span class="p">,</span><span class="n">serial</span><span class="p">,</span><span class="n">uptime</span><span class="p">,</span><span class="n">ip_interfaces</span>
</span></span><span class="line"><span class="cl"><span class="n">r3</span><span class="p">,</span><span class="n">CapeOS</span><span class="o">-</span><span class="n">Pulse</span><span class="p">,</span><span class="mf">4.99.0</span><span class="n">C</span><span class="p">,</span><span class="n">CAPE4S5VG44</span><span class="p">,</span><span class="mi">10</span> <span class="n">minutes</span><span class="p">,</span><span class="mi">4</span>
</span></span><span class="line"><span class="cl"><span class="n">r9</span><span class="p">,,,,,</span>
</span></span></code></pre></div><p>(<code>buf</code> is an <code>io.StringIO</code>, a file that lives in memory, so the REPL can print what would have gone to disk.
The numbers are how many characters each call wrote.)</p>
<p><code>fieldnames</code> fixes the columns and their order, and <code>writeheader()</code> writes them as the first line. A missing
key gives an empty field, as r9 shows. A key that isn&rsquo;t a column is an error, which catches typos:
<code>w.writerow({&quot;hostname&quot;: &quot;r9&quot;, &quot;vendor&quot;: &quot;x&quot;})</code> stops with
<code>ValueError: dict contains fields not in fieldnames: 'vendor'</code>.</p>
<p>The lab&rsquo;s <code>write_csv()</code> opens the file with <code>path.open(&quot;w&quot;, newline=&quot;&quot;)</code> and calls <code>writeheader()</code> and
<code>writerows(rows)</code>, which writes a whole list in one go. <code>newline=&quot;&quot;</code> is the detail to remember: the
<a href="https://docs.python.org/3/library/csv.html">csv module&rsquo;s documentation</a> asks for it on every file you give a
csv writer, because the module writes its own line endings and the file would otherwise translate them again.</p>
<hr>
<h2 id="what-should-a-script-do-when-one-device-doesnt-answer">What should a script do when one device doesn&rsquo;t answer?</h2>
<p>Carry on, and say so at the end. A network always has a device that&rsquo;s down, being replaced, or in the
inventory by mistake, and a tool that stops at the first one gets run once. The starter&rsquo;s <code>run()</code> is a plain
loop, <code>rows.append(facts(d))</code> for each device. With r2 switched off:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl">$ python scripts/inventory.py
</span></span><span class="line"><span class="cl">Traceback (most recent call last):
</span></span><span class="line"><span class="cl">  File &#34;/workspaces/python-101/scripts/inventory.py&#34;, line 37, in &lt;module&gt;
</span></span><span class="line"><span class="cl">    sys.exit(main())
</span></span><span class="line"><span class="cl">             ^^^^^^
</span></span><span class="line"><span class="cl">  File &#34;/workspaces/python-101/scripts/inventory.py&#34;, line 28, in main
</span></span><span class="line"><span class="cl">    rows, failures = run(devices)
</span></span><span class="line"><span class="cl">                     ^^^^^^^^^^^^
</span></span><span class="line"><span class="cl">  File &#34;/workspaces/python-101/netlab/report.py&#34;, line 102, in run
</span></span><span class="line"><span class="cl">    rows.append(facts(d))
</span></span><span class="line"><span class="cl">                ^^^^^^^^
</span></span><span class="line"><span class="cl">  File &#34;/workspaces/python-101/netlab/report.py&#34;, line 55, in facts
</span></span><span class="line"><span class="cl">    raise DeviceError(f&#34;{device[&#39;name&#39;]}: no answer from {device[&#39;host&#39;]}&#34;) from None
</span></span><span class="line"><span class="cl">netlab.devices.DeviceError: r2: no answer from 172.80.111.12
</span></span></code></pre></div><p>Read it from the bottom, as lesson 4 showed: <code>facts()</code> raised <code>DeviceError</code> for r2, nothing caught it, and it
went up through <code>run()</code> and <code>main()</code> until Python stopped. r1 had answered, but no CSV was written, and r3 and
sw1 were never tried. The fix is a <code>try</code> <strong>inside</strong> the loop, around one device:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl">    <span class="n">rows</span><span class="p">,</span> <span class="n">failures</span> <span class="o">=</span> <span class="p">[],</span> <span class="p">{}</span>
</span></span><span class="line"><span class="cl">    <span class="k">for</span> <span class="n">d</span> <span class="ow">in</span> <span class="n">devices</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="k">try</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">            <span class="n">rows</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">facts</span><span class="p">(</span><span class="n">d</span><span class="p">))</span>
</span></span><span class="line"><span class="cl">        <span class="k">except</span> <span class="n">DeviceError</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">            <span class="n">failures</span><span class="p">[</span><span class="n">d</span><span class="p">[</span><span class="s2">&#34;name&#34;</span><span class="p">]]</span> <span class="o">=</span> <span class="nb">str</span><span class="p">(</span><span class="n">e</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="n">rows</span><span class="p">,</span> <span class="n">failures</span>
</span></span></code></pre></div><p>Where the <code>try</code> sits decides what a failure costs. Around the whole loop, one dead router ends the run. Around
one device, it costs that device&rsquo;s row and nothing else. It catches only <code>DeviceError</code>, the &ldquo;couldn&rsquo;t log in
or couldn&rsquo;t reach it&rdquo; that <code>facts()</code> raises on purpose. A typo in your own code raises something else, and
should still stop the script with a traceback, because you want to see it.</p>
<p><code>failures</code> maps a device&rsquo;s name to the reason, so the report can say exactly what happened. With r2 stopped and
r9 in the inventory, a router that was never built:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl">$ time python scripts/inventory.py
</span></span><span class="line"><span class="cl">wrote inventory.csv: 3 of 5 devices
</span></span><span class="line"><span class="cl">  couldn&#39;t inventory r2: no answer from 172.80.111.12
</span></span><span class="line"><span class="cl">  couldn&#39;t inventory r9: no answer from 172.80.111.19
</span></span><span class="line"><span class="cl">python scripts/inventory.py  0.59s user 0.10s system 6% cpu 11.285 total
</span></span></code></pre></div><p>Three rows in the CSV, and two lines naming what&rsquo;s missing and why. &ldquo;No answer&rdquo; is Netmiko&rsquo;s
<code>NetmikoTimeoutException</code>, turned into one line in <code>facts()</code> the way <code>collect()</code> did it in lesson 6.</p>
<hr>
<h2 id="what-is-an-exit-code-and-why-does-the-script-exit-2">What is an exit code, and why does the script exit 2?</h2>
<p>Every program hands the shell a number when it finishes, its <strong>exit code</strong> (or exit status): 0 means it worked,
anything else means something didn&rsquo;t. The shell keeps the last one in <code>$?</code>, and <code>&amp;&amp;</code>, a shell script&rsquo;s <code>if</code>,
cron and every CI pipeline decide what to do next from it. <a href="/lessons/linux-cli-101/">Linux CLI 101</a> covers it
from the shell&rsquo;s side. In Python, <code>main()</code> returns the code and the script&rsquo;s last line hands it over:
<code>sys.exit(main())</code>.</p>
<table>
  <thead>
      <tr>
          <th>Situation</th>
          <th>Exit code</th>
          <th>Who decides it</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td>every device answered</td>
          <td>0</td>
          <td><code>main()</code></td>
      </tr>
      <tr>
          <td>some devices failed; the rest are in the CSV</td>
          <td>2</td>
          <td><code>main()</code></td>
      </tr>
      <tr>
          <td>a bad option, such as <code>--source xml</code></td>
          <td>2</td>
          <td>argparse, before any device is touched</td>
      </tr>
      <tr>
          <td>a bug: an exception nobody caught</td>
          <td>1</td>
          <td>Python</td>
      </tr>
  </tbody>
</table>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl">$ python scripts/inventory.py --source xml; echo $?
</span></span><span class="line"><span class="cl">usage: inventory.py [-h] [--source {yaml,api}] [--out OUT]
</span></span><span class="line"><span class="cl">inventory.py: error: argument --source: invalid choice: &#39;xml&#39; (choose from &#39;yaml&#39;, &#39;api&#39;)
</span></span><span class="line"><span class="cl">2
</span></span></code></pre></div><p>Why 2 and not 1? Python gives an uncaught exception 1, so 1 means &ldquo;the tool broke&rdquo;; 2 here means &ldquo;the tool
worked, part of the network didn&rsquo;t&rdquo;. The catch is that argparse also exits 2 for a bad option, so a caller
can&rsquo;t tell those apart from the number alone. For this tool that&rsquo;s acceptable: a bad option never writes a
CSV, and the message says which it was. There&rsquo;s no universal rule; <code>grep</code>, for example, exits 0 for &ldquo;found&rdquo;,
1 for &ldquo;not found&rdquo; and 2 for an error.</p>
<p>Notice where the output goes, too. The summary goes to <strong>stdout</strong> (standard output) and the failures to
<strong>stderr</strong> (standard error), with <code>file=sys.stderr</code>. A terminal shows both. Redirect the script to a file
with <code>&gt;</code> and only the summary goes there: the failures stay on screen, where a person sees them.</p>
<hr>
<h2 id="how-does-argparse-turn-a-command-line-into-options">How does argparse turn a command line into options?</h2>
<p><code>argparse</code>, in the standard library, reads the words after the script&rsquo;s name, checks them, and gives them
back as one object with an attribute per option. This is the lab&rsquo;s <code>parse_args()</code>:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">parse_args</span><span class="p">(</span><span class="n">argv</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="n">p</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">description</span><span class="o">=</span><span class="s2">&#34;Inventory every lab device to a CSV file.&#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="n">p</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s2">&#34;--source&#34;</span><span class="p">,</span> <span class="n">choices</span><span class="o">=</span><span class="p">[</span><span class="s2">&#34;yaml&#34;</span><span class="p">,</span> <span class="s2">&#34;api&#34;</span><span class="p">],</span> <span class="n">default</span><span class="o">=</span><span class="s2">&#34;yaml&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">                   <span class="n">help</span><span class="o">=</span><span class="s2">&#34;where the device list comes from (default: yaml, the file inventory.yml)&#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="n">p</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s2">&#34;--out&#34;</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="s2">&#34;inventory.csv&#34;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s2">&#34;the CSV file to write (default: inventory.csv)&#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="n">p</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="n">argv</span><span class="p">)</span>
</span></span></code></pre></div><p>Each <code>add_argument()</code> names an option and its rules: <code>default</code> when it isn&rsquo;t given, <code>choices</code> for the only
values allowed, <code>help</code> for the help text. <code>parse_args()</code> returns a <code>Namespace</code>, and <code>args.source</code> and
<code>args.out</code> are the values. <code>argv=None</code> means the real command line; a list lets you try it in the REPL
(here <code>inv</code> is <code>scripts/inventory.py</code>, loaded as a module):</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="o">&gt;&gt;&gt;</span> <span class="n">inv</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([])</span>
</span></span><span class="line"><span class="cl"><span class="n">Namespace</span><span class="p">(</span><span class="n">source</span><span class="o">=</span><span class="s1">&#39;yaml&#39;</span><span class="p">,</span> <span class="n">out</span><span class="o">=</span><span class="s1">&#39;inventory.csv&#39;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="o">&gt;&gt;&gt;</span> <span class="n">inv</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s2">&#34;--source&#34;</span><span class="p">,</span> <span class="s2">&#34;api&#34;</span><span class="p">,</span> <span class="s2">&#34;--out&#34;</span><span class="p">,</span> <span class="s2">&#34;reports/x.csv&#34;</span><span class="p">])</span>
</span></span><span class="line"><span class="cl"><span class="n">Namespace</span><span class="p">(</span><span class="n">source</span><span class="o">=</span><span class="s1">&#39;api&#39;</span><span class="p">,</span> <span class="n">out</span><span class="o">=</span><span class="s1">&#39;reports/x.csv&#39;</span><span class="p">)</span>
</span></span></code></pre></div><p>What you get for free is the reason to use it rather than reading <code>sys.argv</code> yourself. It refuses bad input
with a usage line and exit code 2 before your code runs, as <code>--source xml</code> showed, and <code>--help</code> prints a
page built from the <code>description</code> and each option&rsquo;s <code>help</code>, without a line of code from you.</p>
<p>The <a href="https://docs.python.org/3/library/argparse.html">argparse documentation</a> has the rest: positional
arguments, on/off flags with <code>action=&quot;store_true&quot;</code>, and types.</p>
<hr>
<h2 id="what-would-nornir-add-to-a-tool-like-this">What would Nornir add to a tool like this?</h2>
<p>The same shape, with the next parts already written. <a href="https://nornir.readthedocs.io/">Nornir</a> is a Python
automation framework built around this loop: an inventory of hosts, a task that runs on each one, and a result
per host.</p>
<table>
  <thead>
      <tr>
          <th></th>
          <th>This script</th>
          <th>Nornir</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td>Devices at once</td>
          <td>one at a time, in a <code>for</code> loop</td>
          <td>many at once, in <strong>threads</strong> (several connections waiting in parallel)</td>
      </tr>
      <tr>
          <td>Inventory</td>
          <td>a list of dicts from YAML or the API</td>
          <td>hosts, groups and defaults, from files or plugins (NetBox has one)</td>
      </tr>
      <tr>
          <td>Results</td>
          <td><code>rows</code> and a <code>failures</code> dict you build</td>
          <td>a result per host, with the failed hosts listed for you</td>
      </tr>
  </tbody>
</table>
<p>The first is the one you&rsquo;d notice. A clean run in the lab takes between 6 and 12 seconds for four devices,
most of it waiting for SSH and prompts, and each device that doesn&rsquo;t answer adds its whole 5-second timeout,
because the loop waits for each device in turn. With a few hundred devices that&rsquo;s too slow, and running
connections in parallel safely is a subject of its own.</p>
<p>It&rsquo;s easier to learn once you&rsquo;ve written the loop it replaces: <code>facts()</code> is what Nornir calls a task, <code>run()</code>
is what its runner does, and <code>failures</code> is its failed hosts. Nornir&rsquo;s documentation starts with a tutorial.</p>
<hr>
<h2 id="what-goes-wrong">What goes wrong</h2>
<p><strong>The script stops at the first dead device.</strong> The <code>try</code>/<code>except</code> is around the loop, or missing. Put it
inside the loop, around one device.</p>
<p><strong><code>KeyError: 'version'</code> on r3.</strong> The <code>cisco_ios</code> key was used on an <code>arista_eos</code> device. Print each type&rsquo;s
parsed <code>show version</code> in the REPL before you map keys.</p>
<p><strong>The serial column shows <code>['CAPEHFI5RPW']</code>.</strong> The <code>cisco_ios</code> template gives a list. Take <code>[0]</code>.</p>
<p><strong>The model column is empty.</strong> It came from <code>show version</code>, where these devices leave it blank. Take it from
the inventory.</p>
<p><strong><code>ValueError: dict contains fields not in fieldnames</code>.</strong> A key in the row isn&rsquo;t in <code>COLUMNS</code>, often a typo.
The error names the key.</p>
<p><strong>Every failure is caught, your own bugs included.</strong> <code>except Exception:</code> in <code>run()</code> turns a typo in <code>facts()</code>
into &ldquo;couldn&rsquo;t inventory&rdquo; for every device, with no traceback to find it by. Catch <code>DeviceError</code>.</p>
<p><strong>The script exits 0 when devices failed.</strong> The script calls <code>main()</code> without <code>sys.exit()</code>, or <code>main()</code>
doesn&rsquo;t return the code. Run <code>echo $?</code> straight after the script to see.</p>
<hr>
<h2 id="try-it">Try it</h2>
<p><a href="/labs/python-101/#chapter-8">Chapter 8 of the lab</a> has you write <code>load_devices()</code>, <code>facts()</code> and
<code>write_csv()</code>, and run the script against r1, r2, r3 and sw1. Then <code>make break T=8.2</code> stops r2 and adds a
router that doesn&rsquo;t exist, and you make <code>run()</code> carry on and the script exit 2. Last, <code>--source</code> and <code>--out</code>
with argparse, and proof that the YAML and the API give the same CSV.</p>
<h2 id="whats-next">What&rsquo;s next</h2>
<p>That&rsquo;s Python 101: from <code>2 + 2</code> at the REPL to a tool that logs in to every device in an inventory, reads two
CLIs, and reports what it found and what it couldn&rsquo;t reach. Where next depends on what you want to automate:</p>
<ul>
<li><a href="/lessons/ansible-101/">Ansible 101</a> runs tasks against an inventory without you writing the loop. Python 101
is recommended first: YAML&rsquo;s data shapes, Jinja2&rsquo;s expressions and Ansible&rsquo;s tracebacks all read like the
Python you now know.</li>
<li><span class="link-soon">NetBox</span> makes the inventory a source of truth, with a REST API like the lab&rsquo;s <code>api</code>.
Python 101 is required for it, as it is for <span class="link-soon">network testing</span> and
<span class="link-soon">ANTA</span>.</li>
</ul>
]]></content:encoded></item><item><title>Talking to Devices with Netmiko: SSH from Python (Python 101, Lesson 6)</title><link>https://networkdoodles.com/lessons/python-101/netmiko/</link><pubDate>Mon, 16 Nov 2026 09:00:00 -0500</pubDate><dc:creator>David Henderson</dc:creator><guid>https://networkdoodles.com/lessons/python-101/netmiko/</guid><category>python</category><category>network-automation</category><category>netmiko</category><category>textfsm</category><category>capeos</category><description>Log in to routers from Python with Netmiko: ConnectHandler, send_command with TextFSM, config changes, passwords from the environment, and login errors handled.</description><content:encoded xmlns:content="http://purl.org/rss/1.0/modules/content/"><![CDATA[<p><strong>Netmiko</strong> is a Python library that logs in to network devices over SSH and runs CLI commands for you. One
call, <code>ConnectHandler()</code>, opens the session and gets it ready; <code>send_command()</code> runs a show command and
returns its output, already parsed into a list of dicts if you add <code>use_textfsm=True</code>; <code>send_config_set()</code>
pushes configuration lines. The username and password come from environment variables, never from the code,
and a failed login or a device that doesn&rsquo;t answer arrives as an exception you can catch.</p>
<p>Until now the course has parsed show output saved in files. This lesson gets it from live devices, and takes
a first look at <strong>objects</strong> and <strong>classes</strong>, because the connection Netmiko gives you is one. Every output
below comes from the <a href="/labs/python-101/">lab</a>: Netmiko 4.8.0 against r1 (CapeOS Bolt) and r3 (CapeOS Pulse).</p>
<hr>
<h2 id="what-does-netmiko-do-that-plain-ssh-doesnt">What does Netmiko do that plain SSH doesn&rsquo;t?</h2>
<p>SSH itself only carries bytes: you type, the device sends characters back. The Python library that speaks SSH
is <a href="https://www.paramiko.org/">paramiko</a>, and Netmiko is built on top of it. With paramiko alone you&rsquo;d have to
solve the problems a person at a terminal solves without thinking:</p>
<table>
  <thead>
      <tr>
          <th>Problem</th>
          <th>What a person does</th>
          <th>What Netmiko does</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td><strong>The prompt.</strong> When has the output finished?</td>
          <td>waits until <code>r1#</code> comes back</td>
          <td>learns the prompt at login, and reads until it sees it again</td>
      </tr>
      <tr>
          <td><strong>Paging.</strong> Long output stops at <code>--More--</code></td>
          <td>presses space</td>
          <td>turns paging off at login (<code>terminal length 0</code>)</td>
      </tr>
      <tr>
          <td><strong>Line wrapping.</strong> Wide lines break</td>
          <td>widens the window</td>
          <td>sets the terminal width (<code>terminal width 511</code>)</td>
      </tr>
      <tr>
          <td><strong>Privilege.</strong> Some commands need <code>enable</code></td>
          <td>types <code>enable</code> and the secret</td>
          <td><code>conn.enable()</code>, with <code>secret=</code> given at login</td>
      </tr>
      <tr>
          <td><strong>Config mode.</strong> Changes need <code>configure terminal</code></td>
          <td>types it, then <code>end</code></td>
          <td><code>send_config_set()</code> enters and leaves for you</td>
      </tr>
  </tbody>
</table>
<p>You can watch it happen. Netmiko writes everything it sends and receives to a file if you give it
<code>session_log=&quot;session.log&quot;</code>. This is the log of a login to r1, one <code>show clock</code>, and the logout:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl">r1#
</span></span><span class="line"><span class="cl">r1#terminal width 511
</span></span><span class="line"><span class="cl">r1#terminal length 0
</span></span><span class="line"><span class="cl">r1#
</span></span><span class="line"><span class="cl">r1#
</span></span><span class="line"><span class="cl">r1#show clock
</span></span><span class="line"><span class="cl">05:51:53.965 UTC Wed Nov 11 2026
</span></span><span class="line"><span class="cl">r1#
</span></span><span class="line"><span class="cl">r1#
</span></span><span class="line"><span class="cl">r1#exit
</span></span></code></pre></div><p>The first four lines are Netmiko&rsquo;s <strong>session preparation</strong>, the setup it runs before your first command. The
lab&rsquo;s login lands straight at the privileged <code>r1#</code> prompt, so there&rsquo;s no <code>enable</code> here: <code>conn.check_enable_mode()</code>
returns <code>True</code>. On a device that logs you in at <code>r1&gt;</code>, you&rsquo;d pass <code>secret=</code> to <code>ConnectHandler()</code> and call
<code>conn.enable()</code>.</p>
<p><a href="https://github.com/carlmontanari/scrapli">Scrapli</a> does the same job with a different design, including a
way to run many sessions at once. This course uses <a href="https://github.com/ktbyers/netmiko">Netmiko</a>, the one most
network automation examples are written with.</p>
<hr>
<h2 id="why-does-a-capeos-router-say-cisco_ios">Why does a CapeOS router say cisco_ios?</h2>
<p>Netmiko needs to know what kind of CLI it&rsquo;s talking to, because the commands that turn paging off and the
shape of the prompt differ from one network OS to another. You tell it with <strong><code>device_type</code></strong>, a name from
<a href="https://github.com/ktbyers/netmiko/blob/develop/PLATFORMS.md">Netmiko&rsquo;s list of platforms</a>, such as
<code>cisco_ios</code>, <code>arista_eos</code> or <code>juniper_junos</code>.</p>
<p><a href="/posts/capeos-lab-network-os/">CapeOS</a>, the lab&rsquo;s network OS, has two CLI dialects. <strong>Bolt</strong> (r1, r2 and sw1)
behaves like the CLI that Netmiko and ntc-templates call <code>cisco_ios</code>; <strong>Pulse</strong> (r3) behaves like the one they
call <code>arista_eos</code>. They behave closely enough that both libraries work against it unchanged. So in this lab
the <code>device_type</code> is what picks the dialect:</p>
<table>
  <thead>
      <tr>
          <th>Device</th>
          <th>CapeOS dialect</th>
          <th><code>device_type</code></th>
          <th>Netmiko&rsquo;s class</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td>r1, r2, sw1</td>
          <td>Bolt</td>
          <td><code>cisco_ios</code></td>
          <td><code>CiscoIosSSH</code></td>
      </tr>
      <tr>
          <td>r3</td>
          <td>Pulse</td>
          <td><code>arista_eos</code></td>
          <td><code>AristaSSH</code></td>
      </tr>
  </tbody>
</table>
<p>That doesn&rsquo;t make CapeOS either of those products: it&rsquo;s an open-source OS of its own, and <code>device_type</code> names
the CLI each dialect behaves like. The same name also picks the ntc-templates template (lesson 5) for parsed
output, so a wrong <code>device_type</code> can log in fine and still prepare the session and parse for the wrong CLI.</p>
<hr>
<h2 id="how-do-you-log-in-and-run-a-command">How do you log in and run a command?</h2>
<p><code>ConnectHandler()</code> takes the device&rsquo;s details as <strong>keyword arguments</strong>, <code>name=value</code> pairs, so the order
doesn&rsquo;t matter and each value says what it is. It opens the SSH session, runs the session preparation, and
gives you back the connection:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="o">&gt;&gt;&gt;</span> <span class="kn">import</span> <span class="nn">os</span>
</span></span><span class="line"><span class="cl"><span class="o">&gt;&gt;&gt;</span> <span class="kn">from</span> <span class="nn">netmiko</span> <span class="kn">import</span> <span class="n">ConnectHandler</span>
</span></span><span class="line"><span class="cl"><span class="o">&gt;&gt;&gt;</span> <span class="kn">from</span> <span class="nn">netlab.env</span> <span class="kn">import</span> <span class="n">load_env</span>
</span></span><span class="line"><span class="cl"><span class="o">&gt;&gt;&gt;</span> <span class="n">load_env</span><span class="p">()</span>
</span></span><span class="line"><span class="cl"><span class="o">&gt;&gt;&gt;</span> <span class="n">conn</span> <span class="o">=</span> <span class="n">ConnectHandler</span><span class="p">(</span><span class="n">device_type</span><span class="o">=</span><span class="s2">&#34;cisco_ios&#34;</span><span class="p">,</span> <span class="n">host</span><span class="o">=</span><span class="s2">&#34;r1&#34;</span><span class="p">,</span> <span class="n">username</span><span class="o">=</span><span class="n">os</span><span class="o">.</span><span class="n">environ</span><span class="p">[</span><span class="s2">&#34;LAB_USER&#34;</span><span class="p">],</span> <span class="n">password</span><span class="o">=</span><span class="n">os</span><span class="o">.</span><span class="n">environ</span><span class="p">[</span><span class="s2">&#34;LAB_PASSWORD&#34;</span><span class="p">])</span>
</span></span><span class="line"><span class="cl"><span class="o">&gt;&gt;&gt;</span> <span class="n">conn</span><span class="o">.</span><span class="n">find_prompt</span><span class="p">()</span>
</span></span><span class="line"><span class="cl"><span class="s1">&#39;r1#&#39;</span>
</span></span></code></pre></div><p><code>host</code> can be a name or an address: in the lab, <code>r1</code> resolves to <code>172.80.111.11</code> on the management network.
<code>find_prompt()</code> asks the device for its prompt, the quickest way to prove the login worked.</p>
<p><code>send_command()</code> runs one command and returns everything the device printed, as a single string:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="o">&gt;&gt;&gt;</span> <span class="nb">print</span><span class="p">(</span><span class="n">conn</span><span class="o">.</span><span class="n">send_command</span><span class="p">(</span><span class="s2">&#34;show ip interface brief&#34;</span><span class="p">))</span>
</span></span><span class="line"><span class="cl"><span class="n">Interface</span>              <span class="n">IP</span><span class="o">-</span><span class="n">Address</span>      <span class="n">OK</span><span class="err">?</span> <span class="n">Method</span> <span class="n">Status</span>                <span class="n">Protocol</span>
</span></span><span class="line"><span class="cl"><span class="n">GigabitEthernet0</span>       <span class="mf">172.80.111.11</span>   <span class="n">YES</span> <span class="n">DHCP</span>   <span class="n">up</span>                    <span class="n">up</span>
</span></span><span class="line"><span class="cl"><span class="n">GigabitEthernet1</span>       <span class="mf">192.168.10.1</span>    <span class="n">YES</span> <span class="n">manual</span> <span class="n">up</span>                    <span class="n">up</span>
</span></span><span class="line"><span class="cl"><span class="n">GigabitEthernet2</span>       <span class="mf">10.0.12.1</span>       <span class="n">YES</span> <span class="n">manual</span> <span class="n">up</span>                    <span class="n">up</span>
</span></span><span class="line"><span class="cl"><span class="n">GigabitEthernet3</span>       <span class="mf">10.0.13.1</span>       <span class="n">YES</span> <span class="n">manual</span> <span class="n">up</span>                    <span class="n">up</span>
</span></span><span class="line"><span class="cl"><span class="n">GigabitEthernet4</span>       <span class="n">unassigned</span>      <span class="n">YES</span> <span class="n">unset</span>  <span class="n">administratively</span> <span class="n">down</span> <span class="n">down</span>
</span></span><span class="line"><span class="cl"><span class="n">Loopback0</span>              <span class="mf">10.255.0.1</span>      <span class="n">YES</span> <span class="n">manual</span> <span class="n">up</span>                    <span class="n">up</span>
</span></span></code></pre></div><p>That&rsquo;s the text lessons 2 to 5 parsed by hand, with <code>split()</code>, a regex and TextFSM. Now it comes from the
router instead of a file. <code>send_command()</code> waits for the prompt to come back before it returns, for up to 10
seconds by default (<code>read_timeout=</code>); a slow command such as a large <code>show running-config</code> may need more.</p>
<p><code>conn.disconnect()</code> logs out. A device allows only so many SSH sessions at once (its VTY lines), and a script
that forgets to disconnect holds them until they time out.</p>
<hr>
<h2 id="what-does-use_textfsmtrue-give-you">What does use_textfsm=True give you?</h2>
<p>Add <code>use_textfsm=True</code> and Netmiko hands the output to ntc-templates before returning it. You get the same
list of dicts as <a href="/lessons/python-101/regex-and-textfsm/">lesson 5</a>&rsquo;s <code>parse_output()</code>, with no parsing code
of your own:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="o">&gt;&gt;&gt;</span> <span class="n">rows</span> <span class="o">=</span> <span class="n">conn</span><span class="o">.</span><span class="n">send_command</span><span class="p">(</span><span class="s2">&#34;show ip interface brief&#34;</span><span class="p">,</span> <span class="n">use_textfsm</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="o">&gt;&gt;&gt;</span> <span class="nb">type</span><span class="p">(</span><span class="n">rows</span><span class="p">),</span> <span class="nb">len</span><span class="p">(</span><span class="n">rows</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="p">(</span><span class="o">&lt;</span><span class="k">class</span> <span class="err">&#39;</span><span class="nc">list</span><span class="s1">&#39;&gt;, 6)</span>
</span></span><span class="line"><span class="cl"><span class="o">&gt;&gt;&gt;</span> <span class="n">rows</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span>
</span></span><span class="line"><span class="cl"><span class="p">{</span><span class="s1">&#39;interface&#39;</span><span class="p">:</span> <span class="s1">&#39;GigabitEthernet1&#39;</span><span class="p">,</span> <span class="s1">&#39;ip_address&#39;</span><span class="p">:</span> <span class="s1">&#39;192.168.10.1&#39;</span><span class="p">,</span> <span class="s1">&#39;status&#39;</span><span class="p">:</span> <span class="s1">&#39;up&#39;</span><span class="p">,</span> <span class="s1">&#39;proto&#39;</span><span class="p">:</span> <span class="s1">&#39;up&#39;</span><span class="p">}</span>
</span></span></code></pre></div><p>Six interfaces, six dicts. Ask r3, the Pulse router, the same question with <code>device_type=&quot;arista_eos&quot;</code>:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="o">&gt;&gt;&gt;</span> <span class="n">r3</span> <span class="o">=</span> <span class="n">ConnectHandler</span><span class="p">(</span><span class="n">device_type</span><span class="o">=</span><span class="s2">&#34;arista_eos&#34;</span><span class="p">,</span> <span class="n">host</span><span class="o">=</span><span class="s2">&#34;r3&#34;</span><span class="p">,</span> <span class="n">username</span><span class="o">=</span><span class="n">os</span><span class="o">.</span><span class="n">environ</span><span class="p">[</span><span class="s2">&#34;LAB_USER&#34;</span><span class="p">],</span> <span class="n">password</span><span class="o">=</span><span class="n">os</span><span class="o">.</span><span class="n">environ</span><span class="p">[</span><span class="s2">&#34;LAB_PASSWORD&#34;</span><span class="p">])</span>
</span></span><span class="line"><span class="cl"><span class="o">&gt;&gt;&gt;</span> <span class="n">r3</span><span class="o">.</span><span class="n">send_command</span><span class="p">(</span><span class="s2">&#34;show ip interface brief&#34;</span><span class="p">,</span> <span class="n">use_textfsm</span><span class="o">=</span><span class="kc">True</span><span class="p">)[</span><span class="mi">0</span><span class="p">]</span>
</span></span><span class="line"><span class="cl"><span class="p">{</span><span class="s1">&#39;interface&#39;</span><span class="p">:</span> <span class="s1">&#39;Ethernet1&#39;</span><span class="p">,</span> <span class="s1">&#39;ip_address&#39;</span><span class="p">:</span> <span class="s1">&#39;10.0.13.2/30&#39;</span><span class="p">,</span> <span class="s1">&#39;status&#39;</span><span class="p">:</span> <span class="s1">&#39;up&#39;</span><span class="p">,</span> <span class="s1">&#39;protocol&#39;</span><span class="p">:</span> <span class="s1">&#39;up&#39;</span><span class="p">,</span> <span class="s1">&#39;mtu&#39;</span><span class="p">:</span> <span class="s1">&#39;1500&#39;</span><span class="p">}</span>
</span></span></code></pre></div><p>Same command, different template, and the keys differ: <code>protocol</code> instead of <code>proto</code>, an <code>mtu</code> column, and the
address with its prefix length, because that&rsquo;s how Pulse prints it. Each template&rsquo;s keys come from the
template&rsquo;s author, not from a standard. Code that runs against two device types should use the keys they share
(<code>interface</code>, <code>status</code>) or translate one shape into the other.</p>
<p>If there&rsquo;s no template for a platform and command, <code>use_textfsm=True</code> gives you back the plain string, as if
you hadn&rsquo;t asked. Lesson 5 found that ntc-templates has none for <code>show ntp associations</code> on <code>cisco_ios</code>:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="o">&gt;&gt;&gt;</span> <span class="n">out</span> <span class="o">=</span> <span class="n">conn</span><span class="o">.</span><span class="n">send_command</span><span class="p">(</span><span class="s2">&#34;show ntp associations&#34;</span><span class="p">,</span> <span class="n">use_textfsm</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="o">&gt;&gt;&gt;</span> <span class="nb">type</span><span class="p">(</span><span class="n">out</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="o">&lt;</span><span class="k">class</span> <span class="err">&#39;</span><span class="nc">str</span><span class="s1">&#39;&gt;</span>
</span></span></code></pre></div><p>No error, no warning. A <code>for</code> loop over that string walks it one character at a time, which is a confusing
way to find out.</p>
<hr>
<h2 id="how-do-you-change-the-configuration">How do you change the configuration?</h2>
<p><code>send_config_set()</code> takes a list of configuration lines. It enters configuration mode, sends each line,
leaves again, and returns the whole conversation. Back on r1&rsquo;s connection:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="o">&gt;&gt;&gt;</span> <span class="nb">print</span><span class="p">(</span><span class="n">conn</span><span class="o">.</span><span class="n">send_config_set</span><span class="p">([</span><span class="s2">&#34;interface GigabitEthernet4&#34;</span><span class="p">,</span> <span class="s2">&#34;description spare, configured from Python&#34;</span><span class="p">]))</span>
</span></span><span class="line"><span class="cl"><span class="n">configure</span> <span class="n">terminal</span>
</span></span><span class="line"><span class="cl"><span class="n">Configuration</span> <span class="n">mode</span><span class="p">:</span> <span class="n">one</span> <span class="n">command</span> <span class="n">per</span> <span class="n">line</span><span class="o">.</span> <span class="n">Finish</span> <span class="k">with</span> <span class="s1">&#39;end&#39;</span> <span class="ow">or</span> <span class="n">Ctrl</span><span class="o">-</span><span class="n">Z</span><span class="o">.</span>
</span></span><span class="line"><span class="cl"><span class="n">r1</span><span class="p">(</span><span class="n">config</span><span class="p">)</span><span class="c1">#interface GigabitEthernet4</span>
</span></span><span class="line"><span class="cl"><span class="n">r1</span><span class="p">(</span><span class="n">config</span><span class="o">-</span><span class="k">if</span><span class="p">)</span><span class="c1">#description spare, configured from Python</span>
</span></span><span class="line"><span class="cl"><span class="n">r1</span><span class="p">(</span><span class="n">config</span><span class="o">-</span><span class="k">if</span><span class="p">)</span><span class="c1">#end</span>
</span></span><span class="line"><span class="cl"><span class="n">r1</span><span class="c1">#</span>
</span></span></code></pre></div><p><code>show interfaces description</code> afterwards lists <code>Gi4</code> with its new description.</p>
<p>Read that output, because by default Netmiko doesn&rsquo;t judge it. r1 has no <code>GigabitEthernet9</code>, and this is
what comes back for it, with no exception:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="o">&gt;&gt;&gt;</span> <span class="nb">print</span><span class="p">(</span><span class="n">conn</span><span class="o">.</span><span class="n">send_config_set</span><span class="p">([</span><span class="s2">&#34;interface GigabitEthernet9&#34;</span><span class="p">]))</span>
</span></span><span class="line"><span class="cl"><span class="n">configure</span> <span class="n">terminal</span>
</span></span><span class="line"><span class="cl"><span class="n">Configuration</span> <span class="n">mode</span><span class="p">:</span> <span class="n">one</span> <span class="n">command</span> <span class="n">per</span> <span class="n">line</span><span class="o">.</span> <span class="n">Finish</span> <span class="k">with</span> <span class="s1">&#39;end&#39;</span> <span class="ow">or</span> <span class="n">Ctrl</span><span class="o">-</span><span class="n">Z</span><span class="o">.</span>
</span></span><span class="line"><span class="cl"><span class="n">r1</span><span class="p">(</span><span class="n">config</span><span class="p">)</span><span class="c1">#interface GigabitEthernet9</span>
</span></span><span class="line"><span class="cl">                     <span class="o">^</span>
</span></span><span class="line"><span class="cl"><span class="o">%</span> <span class="n">Invalid</span> <span class="nb">input</span> <span class="n">detected</span> <span class="n">at</span> <span class="s1">&#39;^&#39;</span> <span class="n">marker</span><span class="o">.</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="n">r1</span><span class="p">(</span><span class="n">config</span><span class="p">)</span><span class="c1">#end</span>
</span></span><span class="line"><span class="cl"><span class="n">r1</span><span class="c1">#</span>
</span></span></code></pre></div><p>The refusal is in the returned string, and your code has to look for it. A change that works is in the
running configuration only, as if you&rsquo;d typed it; saving it is a separate command. Pushing configuration from
a loop is fast in both directions, which is why tools such as <a href="/lessons/ansible-101/">Ansible</a> wrap it in
checks, dry runs and diffs.</p>
<hr>
<h2 id="where-should-the-password-live">Where should the password live?</h2>
<p>Not in the code. A script gets copied, pasted into chat, committed to Git and shared, and a password written
in it goes everywhere the script goes. Git keeps it in the history even after you delete the line.
<a href="/posts/donthardcodepasswords/">Don&rsquo;t hardcode passwords</a> covers the same idea for Ansible.</p>
<p>The usual answer is an <strong>environment variable</strong>: a named value the shell hands to every program it starts
(Linux CLI 101 covers <code>export</code> and <code>env</code>). Python reads them from <code>os.environ</code>, a dict-like object:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="o">&gt;&gt;&gt;</span> <span class="n">os</span><span class="o">.</span><span class="n">environ</span><span class="p">[</span><span class="s2">&#34;LAB_USER&#34;</span><span class="p">]</span>
</span></span><span class="line"><span class="cl"><span class="s1">&#39;admin&#39;</span>
</span></span></code></pre></div><p>To save typing <code>export</code> in every terminal, the values go in a file called <strong><code>.env</code></strong>, one <code>KEY=value</code> per line,
in the project folder. The lab&rsquo;s has the login and the API&rsquo;s token in it. <code>make setup</code> copies it from
<code>.env.example</code>, and <code>.gitignore</code> lists <code>.env</code>, so Git never picks it up. The lab&rsquo;s <code>netlab/env.py</code> has a small
<code>load_env()</code> that reads <code>.env</code> into <code>os.environ</code>, the same thing the
<a href="https://pypi.org/project/python-dotenv/">python-dotenv</a> package does; a variable already set in your shell
wins over the file.</p>
<p>So the code names the variable, and the value lives somewhere else:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="n">password</span><span class="o">=</span><span class="n">os</span><span class="o">.</span><span class="n">environ</span><span class="p">[</span><span class="s2">&#34;LAB_PASSWORD&#34;</span><span class="p">]</span>
</span></span></code></pre></div><p>The lab&rsquo;s check for task 6.1 tests this both ways. It fails if the lab&rsquo;s password appears anywhere in your
code, and it logs in with a deliberately wrong <code>LAB_PASSWORD</code> in the environment, expecting the login to fail.
If your code still gets in, the password didn&rsquo;t come from the environment.</p>
<hr>
<h2 id="what-happens-when-the-login-fails">What happens when the login fails?</h2>
<p>Netmiko raises an <strong>exception</strong>, the same mechanism as the <code>FileNotFoundError</code> in
<a href="/lessons/python-101/files-and-errors/">lesson 4</a>. A wrong password gives this, trimmed to its last part:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl">&gt;&gt;&gt; ConnectHandler(device_type=&#34;cisco_ios&#34;, host=&#34;r1&#34;, username=&#34;admin&#34;, password=&#34;wrong&#34;)
</span></span><span class="line"><span class="cl">Traceback (most recent call last):
</span></span><span class="line"><span class="cl">  ...
</span></span><span class="line"><span class="cl">paramiko.ssh_exception.AuthenticationException: Authentication failed.
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">During handling of the above exception, another exception occurred:
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">Traceback (most recent call last):
</span></span><span class="line"><span class="cl">  ...
</span></span><span class="line"><span class="cl">netmiko.exceptions.NetmikoAuthenticationException: Authentication to device failed.
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">Common causes of this problem are:
</span></span><span class="line"><span class="cl">1. Invalid username and password
</span></span><span class="line"><span class="cl">2. Incorrect SSH-key file
</span></span><span class="line"><span class="cl">3. Connecting to the wrong device
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">Device settings: cisco_ios r1:22
</span></span></code></pre></div><p>Two tracebacks, read from the bottom up: paramiko failed to authenticate, and Netmiko caught that and raised
its own, clearer exception. A device that doesn&rsquo;t answer at all, here an address with nothing on it, gives a
different one after <code>conn_timeout</code> seconds (10 by default; the lab uses 5), with paramiko&rsquo;s
<em>Unable to connect to port 22 on 172.80.111.19</em> underneath:</p>
<p><code>netmiko.exceptions.NetmikoTimeoutException: TCP connection to device failed.</code></p>
<table>
  <thead>
      <tr>
          <th>Exception</th>
          <th>Means</th>
          <th>Usual cause</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td><code>NetmikoAuthenticationException</code></td>
          <td>SSH connected, the login was refused</td>
          <td>wrong username or password, wrong <code>.env</code></td>
      </tr>
      <tr>
          <td><code>NetmikoTimeoutException</code></td>
          <td>nothing answered on port 22</td>
          <td>the device is down, wrong address, a firewall</td>
      </tr>
  </tbody>
</table>
<p>Both live in <code>netmiko.exceptions</code>, so you can catch each one with <code>try</code>/<code>except</code> and say what happened in
one line that names the device:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="kn">from</span> <span class="nn">netmiko.exceptions</span> <span class="kn">import</span> <span class="n">NetmikoAuthenticationException</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="k">try</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">    <span class="n">conn</span> <span class="o">=</span> <span class="n">ConnectHandler</span><span class="p">(</span><span class="n">device_type</span><span class="o">=</span><span class="s2">&#34;cisco_ios&#34;</span><span class="p">,</span> <span class="n">host</span><span class="o">=</span><span class="s2">&#34;r1&#34;</span><span class="p">,</span> <span class="n">username</span><span class="o">=</span><span class="n">user</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="n">password</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="k">except</span> <span class="n">NetmikoAuthenticationException</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">    <span class="nb">print</span><span class="p">(</span><span class="s2">&#34;r1: login failed&#34;</span><span class="p">)</span>
</span></span></code></pre></div><p>The person running the script reads one line instead of two screens of traceback, and it tells them what to
fix.</p>
<hr>
<h2 id="what-is-an-object-and-what-is-a-class">What is an object, and what is a class?</h2>
<p>Look at what <code>ConnectHandler()</code> returned:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="o">&gt;&gt;&gt;</span> <span class="n">conn</span>
</span></span><span class="line"><span class="cl"><span class="o">&lt;</span><span class="n">netmiko</span><span class="o">.</span><span class="n">cisco</span><span class="o">.</span><span class="n">cisco_ios</span><span class="o">.</span><span class="n">CiscoIosSSH</span> <span class="nb">object</span> <span class="n">at</span> <span class="mh">0xffff9c629cd0</span><span class="o">&gt;</span>
</span></span><span class="line"><span class="cl"><span class="o">&gt;&gt;&gt;</span> <span class="n">conn</span><span class="o">.</span><span class="n">base_prompt</span>
</span></span><span class="line"><span class="cl"><span class="s1">&#39;r1&#39;</span>
</span></span></code></pre></div><p><code>conn</code> is an <strong>object</strong>: a value that holds data and also has functions of its own. The data are its
<strong>attributes</strong>, read with a dot: <code>conn.base_prompt</code> is the prompt without the <code>#</code>. The functions are its
<strong>methods</strong>, called with a dot and parentheses: <code>conn.send_command(...)</code>, <code>conn.disconnect()</code>. You&rsquo;ve used
methods since lesson 2, because a string is an object too: <code>line.split()</code> is the <code>split</code> method of one
string.</p>
<p>A <strong>class</strong> is the kind of object, the blueprint every object of that kind is made from. <code>conn</code> is a
<code>CiscoIosSSH</code>; <code>r3</code> above is an <code>AristaSSH</code>. They&rsquo;re different classes with the same method names, so
<code>send_command()</code> works on both, and each does the right thing for its CLI. That&rsquo;s why the code doesn&rsquo;t
change between Bolt and Pulse: only <code>device_type</code> does, and <code>ConnectHandler()</code> picks the class from it.</p>
<p>You can make classes of your own. This course needs only one, and it&rsquo;s the simplest kind: a <strong>dataclass</strong>,
a class that only holds a few named values. The lab&rsquo;s inventory of devices uses one:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="kn">from</span> <span class="nn">dataclasses</span> <span class="kn">import</span> <span class="n">dataclass</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="nd">@dataclass</span>
</span></span><span class="line"><span class="cl"><span class="k">class</span> <span class="nc">Device</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">    <span class="n">name</span><span class="p">:</span> <span class="nb">str</span>
</span></span><span class="line"><span class="cl">    <span class="n">host</span><span class="p">:</span> <span class="nb">str</span>
</span></span><span class="line"><span class="cl">    <span class="n">device_type</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s2">&#34;cisco_ios&#34;</span>
</span></span></code></pre></div><p>The lines inside list the <strong>fields</strong>, each with a type (<code>str</code>, a string) that Python records but doesn&rsquo;t
enforce. <code>= &quot;cisco_ios&quot;</code> is a default, like a function&rsquo;s default argument. The <code>@dataclass</code> line above the
class (a <strong>decorator</strong>) writes the rest for you: a way to create one, a readable printout, and <code>==</code> that
compares the fields:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="o">&gt;&gt;&gt;</span> <span class="n">d</span> <span class="o">=</span> <span class="n">Device</span><span class="p">(</span><span class="s2">&#34;r3&#34;</span><span class="p">,</span> <span class="s2">&#34;172.80.111.13&#34;</span><span class="p">,</span> <span class="s2">&#34;arista_eos&#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="o">&gt;&gt;&gt;</span> <span class="n">d</span>
</span></span><span class="line"><span class="cl"><span class="n">Device</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">&#39;r3&#39;</span><span class="p">,</span> <span class="n">host</span><span class="o">=</span><span class="s1">&#39;172.80.111.13&#39;</span><span class="p">,</span> <span class="n">device_type</span><span class="o">=</span><span class="s1">&#39;arista_eos&#39;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="o">&gt;&gt;&gt;</span> <span class="n">Device</span><span class="p">(</span><span class="s2">&#34;r1&#34;</span><span class="p">,</span> <span class="s2">&#34;172.80.111.11&#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="n">Device</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">&#39;r1&#39;</span><span class="p">,</span> <span class="n">host</span><span class="o">=</span><span class="s1">&#39;172.80.111.11&#39;</span><span class="p">,</span> <span class="n">device_type</span><span class="o">=</span><span class="s1">&#39;cisco_ios&#39;</span><span class="p">)</span>
</span></span></code></pre></div><p>Why not a dict? <code>d.host</code> is shorter than <code>d[&quot;host&quot;]</code>, making one with a field missing fails at once (a
<code>TypeError</code>) where a dict would quietly lack the key, and the printout says what the thing is. The
<a href="https://docs.python.org/3/library/dataclasses.html">dataclasses documentation</a> has the rest. Classes that
build on other classes (<strong>inheritance</strong>) wait for ANTA, where every test you
<span class="link-soon">write yourself</span> is a class built on ANTA&rsquo;s <code>AntaTest</code>.</p>
<hr>
<h2 id="how-does-one-script-talk-to-every-device">How does one script talk to every device?</h2>
<p>With a list of <code>Device</code>s and a loop: connect, run the command, disconnect, keep the result in a dict under the
device&rsquo;s name. That&rsquo;s <code>collect()</code>, the function task 6.2 asks for, and the lab&rsquo;s <code>scripts/collect.py</code> prints a
line per device from what it returns:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl">$ python scripts/collect.py
</span></span><span class="line"><span class="cl">r1   6 IP interfaces, 5 up
</span></span><span class="line"><span class="cl">r2   6 IP interfaces, 5 up
</span></span><span class="line"><span class="cl">sw1  10 IP interfaces, 4 up
</span></span><span class="line"><span class="cl">r3   4 IP interfaces, 4 up
</span></span></code></pre></div><p>Three Bolt devices and a Pulse router, through one function, because each <code>Device</code> carries its own
<code>device_type</code>. The <code>disconnect()</code> goes in a <code>finally:</code> block, so the session is closed even when the command
fails. With r2&rsquo;s password changed (the lab&rsquo;s <code>make break T=6.2</code>), the same script stops at r2 with one line,
and exits 1 so a shell script or a CI job can tell it failed:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl">$ python scripts/collect.py
</span></span><span class="line"><span class="cl">error: r2: login failed (check LAB_USER and LAB_PASSWORD)
</span></span></code></pre></div><p>The devices are done one at a time, and the first failure stops the run. Lesson 8 carries on past failures;
Nornir, in a later course, runs the same work on many devices at once.</p>
<hr>
<h2 id="what-goes-wrong">What goes wrong</h2>
<p><strong><code>KeyError: 'LAB_PASSWORD'</code>.</strong> The variable isn&rsquo;t set: <code>.env</code> is missing (<code>make setup</code> makes it), or
<code>load_env()</code> wasn&rsquo;t called before <code>os.environ</code> was read.</p>
<p><strong>The password is in the code &ldquo;for now&rdquo;.</strong> It ends up in Git and in every copy of the script. Read it from the
environment from the first line.</p>
<p><strong><code>NetmikoAuthenticationException</code>, though <code>ssh</code> by hand works.</strong> Compare <code>.env</code> with what you typed, username
included.</p>
<p><strong><code>NetmikoTimeoutException</code>.</strong> Nothing answered on port 22. Check the address and that the device is up before
suspecting the code.</p>
<p><strong>The wrong <code>device_type</code>.</strong> The login may work, but the session preparation and the template are for another
CLI. Use the name your inventory gives that device.</p>
<p><strong><code>use_textfsm=True</code> returns a string.</strong> No template for that platform and command. Check <code>type()</code> before
looping.</p>
<p><strong>Sessions left open, and unread config output.</strong> Put <code>disconnect()</code> in a <code>finally:</code> block, and look for
<code>% Invalid</code> in what <code>send_config_set()</code> returns.</p>
<hr>
<h2 id="try-it">Try it</h2>
<p><a href="/labs/python-101/#chapter-6">Chapter 6 of the lab</a> has you write <code>connect()</code> and <code>interface_table()</code> with the
login read from <code>.env</code>, and run a script that prints r1&rsquo;s interfaces. Then you write the <code>Device</code> dataclass
and <code>collect()</code>, log in to r1, r2, sw1 and r3 (two device types through one function), and turn a refused
login into one clear line instead of a traceback.</p>
<h2 id="whats-next">What&rsquo;s next</h2>
<p>So far the list of devices is written in the script. <a href="/lessons/python-101/yaml-json-rest/">Lesson 7</a> moves it
out, into a YAML inventory file and then a REST API, and shows that both end up as the same list of dicts.</p>
]]></content:encoded></item></channel></rss>