官术网_书友最值得收藏!

Our first Paramiko program

Our first program will use the same general structure of the Pexpect program as far as looping over a list of devices and commands, with the exception of using Paramiko instead of Pexpect. This will give us a good compare and contrast of the differences between the two programs.

You can download the the code from the book GitHub repository, https://github.com/PacktPublishing/Mastering-Python-Networking. I will list out the notable differences here:

 devices = {'iosv-1': {'ip': '172.16.1.20'}, 'iosv-2': {'ip': '172.16.1.21'}}

We no longer need to match the device prompt using Paramiko, therefore, the device dictionary can be simplified:

   commands = ['show version', 'show run']

There is no send line equivalent in Paramiko, so we are manually including the newline break in each of the commands:

  def clear_buffer(connection):
if connection.recv_ready():
return connection.recv(max_buffer)

We are including a new method to clear the buffer for sending commands such as terminal length 0 or enable because we do not need to the output for those commands. We simply want to clear the buffer and get to the execution prompt. This function will later on be used in the loop such as in line 25:

      output = clear_buffer(new_connection)

The rest of the program should be pretty self explanatory, as we have seen the usage in this chapter. The last thing I would like to point out is that since this is an interactive program, we placed some buffer and wait for the command to be finished on the remote device before retrieving the output:

time.sleep(2)

After we clear the buffer, during the time in-between the execution of commands, we will wait two seconds. This will ensure us to give the device adequate time in case it is busy.

主站蜘蛛池模板: 蓬莱市| 甘南县| 冷水江市| 玛曲县| 高雄市| 青川县| 武城县| 临潭县| 花垣县| 梨树县| 广南县| 满洲里市| 晋宁县| 玛曲县| 襄垣县| 德清县| 汤阴县| 大竹县| 华坪县| 江华| 东山县| 汉源县| 桂阳县| 郯城县| 云安县| 道孚县| 澎湖县| 准格尔旗| 武威市| 静安区| 德兴市| 黎城县| 比如县| 贵州省| 成武县| 衡山县| 虹口区| 关岭| 尉氏县| 彭阳县| 武鸣县|