python3 paramiko 巡检网络设备
运维少年 运维少年
巡检网络设备
用paramiko做网络设备巡检,发现大坑,就是show run这种看配置有多页存在的没法显示第二页,没找到paramiko翻页的地方,添加多个空格也不是很好使。
- 避开这个坑,自动登入搞定了后面命令怎么传都是小事了,传参参考第二个脚本吧。
cisco的全页打印显示配置信息的命令:
terminal length 0
show run
华为和H3C的全页打印显示配置信息的命令:
user-interface vty 0 4
screen-length 0
display current-configuration
- 直接在命令里面传入全局模式密码。
#!/usr/bin/python3
# -*- coding:utf-8 -*-
import paramiko
import time
def main(host, username, password, commands):
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(host, username=username, password=password,
port=22, allow_agent=False, look_for_keys=False)
channel = client.invoke_shell() # 请求交互式Shell会话
for command in commands:
channel.send(command + "\n") # 发送指令
while not channel.recv_ready(): # 等待数据到达
time.sleep(1)
output = channel.recv(40960) # 从通道接收数据 nbytes(int)–读取的最大字节数
print(output.decode())
client.close()
if __name__ == '__main__':
host = '192.168.208.131'
username = 'root'
password = 'root.123'
commands = ['enable', 'cisco', 'terminal length 0','show run', 'show ip int br', 'exit'] #全页打印terminal length 0
main(host, username, password, commands)
- 多添加几个空格还是没有解决翻页的问题,最早用pexpect写的,可以避开这个坑,就是灵活性太低。遇到ssh公钥改变的就连不上了,每个厂家都要重写...
#!/usr/bin/python
#-*- coding:utf-8 -*-
import pexpect
import sys
import time
def main(host,username,password,enable,commands):
# host = '192.168.208.131'
# username = 'root'
# password = 'root.123'
# enable = 'cisco'
# commands = [ show processes memory ]
commands = str(commands).split(';')
child = pexpect.spawnu('ssh %s@%s' % (username,host))
child.logfile = sys.stdout
login = child.expect(['yes/no', '[P|p]assword:', pexpect.EOF, pexpect.TIMEOUT])
if login == 0:
child.sendline('yes')
child.expect('[P|p]assword:')
child.sendline('%s' % password)
elif login == 1:
child.sendline('%s' % password)
child.expect('\>')
child.sendline('enable')
child.expect('[P|p]assword:')
child.sendline('%s' % enable)
for command in commands:
child.expect('\#')
child.sendline('%s' % command)
index = child.expect(['--More--','\#'])
if index == 0:
for i in range(5):
child.send(' ')
time.sleep(1)
#child.sendline(' ')
child.sendline('')
#time.sleep(2)
child.expect('\#')
child.sendline('exit')
child.close()
if __name__ == '__main__':
host = sys.argv[1]
username = sys.argv[2]
password = sys.argv[3]
enable = sys.argv[4]
commands = sys.argv[5]
main(host,username,password,enable,commands)