Before reading further, make yourself familiar with How to Install Python and SSH with Python
Here’s modified code which will login into the device, execute the command and save into file called sh_ver.txt. If the file is not created, it will automatically create the file. This script overwrites contents of the file every time it is executed:
import paramiko
host = '192.168.1.66'
user = 'cisco'
secret = 'cisco'
port = 22
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) #Set policy to use when connecting to servers without a known host key
ssh.connect(hostname=host, username=user, password=secret, port=port)
stdin, stdout, stderr = ssh.exec_command('sh ver')
output = stdout.readlines()
#print (''.join(output))
file = open('sh_ver.txt', 'w')
file.write(''.join(output))
file.close()
This would produce the following result:
Cisco IOS Software, 2800 Software (C2800NM-ADVIPSERVICESK9-M), Version 12.4(15)T14, RELEASE SOFTWARE (fc2)
Technical Support: http://www.cisco.com/techsupport
Copyright (c) 1986-2010 by Cisco Systems, Inc.
Compiled Tue 17-Aug-10 09:00 by prod_rel_team
ROM: System Bootstrap, Version 12.4(13r)T, RELEASE SOFTWARE (fc1)
R1 uptime is 1 hour, 59 minutes
System returned to ROM by power-on
System image file is "flash:c2800nm-advipservicesk9-mz.124-15.T14.bin"
This product contains cryptographic features and is subject to United
States and local country laws governing import, export, transfer and
use. Delivery of Cisco cryptographic products does not imply
third-party authority to import, export, distribute or use encryption.
Importers, exporters, distributors and users are responsible for
compliance with U.S. and local country laws. By using this product you
agree to comply with applicable laws and regulations. If you are unable
to comply with U.S. and local laws, return this product immediately.
A summary of U.S. laws governing Cisco cryptographic products may be found at:
http://www.cisco.com/wwl/export/crypto/tool/stqrg.html
If you require further assistance please contact us by sending email to
export@cisco.com.
Cisco 2811 (revision 53.51) with 249856K/12288K bytes of memory.
Processor board ID FHK1223F50J
2 FastEthernet interfaces
1 Virtual Private Network (VPN) Module
DRAM configuration is 64 bits wide with parity enabled.
239K bytes of non-volatile configuration memory.
62720K bytes of ATA CompactFlash (Read/Write)
Configuration register is 0x2102
If we remove file.write(’‘.join(output)) and replace with file.write(output) we would receive the following error:
file.write(output)
TypeError: write() argument must be str, not list
Basically .join() modifies a list into a string.
The problem with the output above is unwanted empty lines because readlines() method adds additional /n at the end of each sequence. The reason readlines keeps the newline character is so you can distinguish between an empty line (has the newline) and the end of the file (empty string).
We have to apply rstrip to each item in the list to remove extra empty lines, not the list itself. If we try to apply rstrip/strip to output we would receive the following error:
AttributeError: 'list' object has no attribute 'rstrip'
or
for line in output.strip('\n'):
AttributeError: 'list' object has no attribute 'strip'
We have to apply rstrip to each item in the list, not the list itself.
Here are two ways to do it:
#1: modify the list in a for-loop
for i, item in enumerate(mylist):
mylist[i] = item.rstrip()
#2: make a new list with a list comprehension
mylist = [item.rstrip() for item in mylist]
Of the two, we’ll do the second method and modify the code as follows:
import paramiko
host = '192.168.1.66'
user = 'cisco'
secret = 'cisco'
port = 22
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) #Set policy to use when connecting to servers without a known host key
ssh.connect(hostname=host, username=user, password=secret, port=port)
stdin, stdout, stderr = ssh.exec_command('sh ver')
list = stdout.readlines()
output = [line.rstrip() for line in list]
#print (''.join(output))
file = open('sh_ver.txt', 'w')
file.write('\n'.join(output))
file.close()
So the output in the file is saved as
Cisco IOS Software, 2800 Software (C2800NM-ADVIPSERVICESK9-M), Version 12.4(15)T14, RELEASE SOFTWARE (fc2)
Technical Support: http://www.cisco.com/techsupport
Copyright (c) 1986-2010 by Cisco Systems, Inc.
Compiled Tue 17-Aug-10 09:00 by prod_rel_team
ROM: System Bootstrap, Version 12.4(13r)T, RELEASE SOFTWARE (fc1)
R1 uptime is 1 hour, 42 minutes
System returned to ROM by power-on
System image file is "flash:c2800nm-advipservicesk9-mz.124-15.T14.bin"
This product contains cryptographic features and is subject to United
States and local country laws governing import, export, transfer and
use. Delivery of Cisco cryptographic products does not imply
third-party authority to import, export, distribute or use encryption.
Importers, exporters, distributors and users are responsible for
compliance with U.S. and local country laws. By using this product you
agree to comply with applicable laws and regulations. If you are unable
to comply with U.S. and local laws, return this product immediately.
A summary of U.S. laws governing Cisco cryptographic products may be found at:
http://www.cisco.com/wwl/export/crypto/tool/stqrg.html
If you require further assistance please contact us by sending email to
export@cisco.com.
Cisco 2811 (revision 53.51) with 249856K/12288K bytes of memory.
Processor board ID FHK1223F50J
2 FastEthernet interfaces
1 Virtual Private Network (VPN) Module
DRAM configuration is 64 bits wide with parity enabled.
239K bytes of non-volatile configuration memory.
62720K bytes of ATA CompactFlash (Read/Write)
Configuration register is 0x2102