python利用paramiko模块进行批量路由交换配置保存

#-*-coding:utf-8-*-

import paramiko, time, tcping, re


def main():
    ip = ['10.0.0.107', '10.0.0.108', '10.0.0.109', '10.0.0.110']
    for i in ip:        
        ping = tcping.Ping(i, 22)  
        ping.ping(2)  
        ret = ping.result.raw 
        results = re.findall(r"connections,(.*?)successed,",ret)
        ping_result = int(results[0].strip())
        
        if (ping_result != 0):  
            # 连接ssh服务器
            ssh_client = paramiko.SSHClient()
            #set_missing_host_key_policy方法,是制定连接远程主机没有本地密钥或HostKeys对象是的策略,AutoAddPolicy,自动添加主机名及主机密钥到本地HostKeys对象,并保存,不依赖load_system_host_keys()的配置,即使~/.ssh/known_hosts不存在也不产生影响。
            ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            
            # - allow_agent: 是否允许使用代理验证,默认为False
            # - look_for_keys: 是否在本地寻找私钥文件,默认为False
            ssh_client.connect(hostname=i, port=22, username="admin", password="admin", allow_agent=False, look_for_keys=False)

            #进入设备交互状态
            command = ssh_client.invoke_shell()
            time.sleep(1)
            command.send('screen-length 0 temporary  \n')
            time.sleep(1)
            command.send('dis curr \n')
            time.sleep(2) 
            output=command.recv(65535).decode('ascii')
            print(output)
            times = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())
            with open(f'd:\\{i}_{times}.txt', "w") as backup:
                backup.write(output)
            print(f'{i} 保存成功')            
            ssh_client.close() 
            print('-*-' * 20)   #分割线             
        else:
            print("{} is not open!!!".format(i))

if __name__ == '__main__':
    main()

你可能感兴趣的:(python,网络安全,python,开发语言)