前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python 网络设备远程自动化

python 网络设备远程自动化

作者头像
以谁为师
发布2019-05-28 20:26:17
1.5K0
发布2019-05-28 20:26:17
举报

telnetlib 远程telnet库 paramiko 远程ssh库

ssh批量按时备份网络设备配置

代码语言:javascript
复制
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    try:
        ssh.connect(
            hostname=host,
            username=user,
            password=passwd,
            port=22,
            pkey=None, look_for_keys=False,
            timeout=3, allow_agent=False)
        remote_conn = ssh.invoke_shell()
        time.sleep(0.1) # 设置间隔


        for cmdline in cmdlist:
            remote_conn.send("%s\n" % cmdline)
            time.sleep(0.5)

        output = remote_conn.recv(1000).decode()
        devname = re.findall(r'\<(.*)\>.*',output)[0] #正则导入主机名
        remote_conn.send('rename startup.cfg %s-%s.cfg-%s\n' % (devname,host,date))
        time.sleep(1)


        remote_conn.send('save\n')  #保存设备当前配置
        time.sleep(0.5)
        save = remote_conn.recv(1000).decode()
        if save.find('written') > -1:
            remote_conn.send("Y\n")
            time.sleep(1)
           # print(remote_conn.recv(1000))
            remote_conn.send("\n")
            # print(remote_conn.recv(1000))
            remote_conn.send("Y\n")
            # time.sleep(5)
            # print(remote_conn.recv(1000))

py2 telnet远程执行

代码语言:javascript
复制
import telnetlib
import re,time,datetime
import sys
reload(sys)
sys.setdefaultencoding("utf-8")


DEBUG =  False  # False 读取host.txt列表主机



cmdlist = [
"ftp 36.27.209.xx",
"ftp",
"ftpxxx",
"cd net_config"
]




def run(host):
    now = datetime.datetime.now()
    today = now.strftime('%Y%m%d')
    logdate = now.strftime("%b %d %H:%M:%S")
    try:
        telnetsession = telnetlib.Telnet(host,timeout=10)  # 实例化telnet对象,建立一个主机连接
        #print (telnetsession.timeout)

        #telnetsession.set_debuglevel(1) # 开启调试,按需开启,方便判断

        telnetsession.write(user + "\n")
        telnetsession.read_very_lazy()
        telnetsession.write(pwd + "\n")
        #登录认证

        # 如果登录成功,则出现类似<R1>,使用UsermodTag来进行捕获
        response = telnetsession.read_until('>')
        devname = re.findall(r'\<(.*)\>.*',response)[0] #正则导入主机名
        #print(devname) 
        if response.find('>') > -1:
            print("INFO:\t%s\t[\033[1;32m%s\033[0m] Login successfully ..." % (logdate, host))

            for cmdline in cmdlist:

                telnetsession.write("%s\n" % cmdline)
                telnetsession.read_very_lazy()



            response = telnetsession.read_until('changed') 
            #read_until()来判断缓冲区中的数据是否有想要的内容,如果没有就等待
            telnetsession.write("put startup.cfg %s-%s-%s.cfg\n" % (devname,host,today))
            telnetsession.close()



    except Exception as e:
        print(e, type(e))
    finally:

        # 执行完毕后,关闭连接

        print("INFO:\t%s\t[\033[1;32m%s\033[0m] Session Close ..." % (logdate, host))
        telnetsession.read_until('complete')

        telnetsession.write("quit\n")
        telnetsession.close()


if __name__ == '__main__':
    ### 配置登录信息
    user = 'admin'
    pwd = raw_input("输入密码:")
    host = '192.168.16.2'

    if not DEBUG:
        with open("host.txt") as f:

            for host in f:
                h = host.strip()
                run(h)


    else: #测试
        run(host)

ssh 批量远程执行例2

代码语言:javascript
复制
import paramiko
import time
import pprint
import socket
import re

DEBUG = True  # False 读取host.txt列表主机


user = 'root'
passwd = input('输入密码: ')

hostlist = [
    'account-98-1',
    'account-98-10',
]

cmdlist = [
    "ls /root",
    "touch /tmp/paramiko.py"
]


def run(host):
    date = time.strftime("%b %d %H:%M:%S", time.localtime())
    print("INFO:\t%s\t[\033[1;32m%s\033[0m] Trying to connect ..." % (date, host))
    paramiko.util.log_to_file('paramiko.log')

    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    count = 0
    try:
        ssh.connect(
            hostname=host,
            username=user,
            password=passwd,
            port=22,
            pkey=None, look_for_keys=False,
            timeout=3, allow_agent=False)

        for cmdline in cmdlist:
            count += 1
            stdin, stdout, stderr = ssh.exec_command(cmdline)
            print("INFO:\t%s\t\033[1;34m[%s]\033[0m\t%s" %
                  (date, count, cmdline))
        results['successful'].append(host)

    except (paramiko.ssh_exception.AuthenticationException,) as e:
        print("INFO:\t%s\t\033[1;31mLogin failed\033[0m\t%s" % (date, e))
        results['unsuccessful'].append(host)
    except (paramiko.ssh_exception.NoValidConnectionsError, socket.gaierror, socket.timeout, socket.error) as e:
        print("INFO:\t%s\t\033[1;31mConnection failed\033[0m\t%s" % (date, e))
        results['unsuccessful'].append(host)
    except Exception as e:
        print(e, type(e))
    finally:
        ssh.close()


if __name__ == '__main__':
    results = {
        'unsuccessful': [],
        'successful': [],
    }

    if not DEBUG:
        with open("host.txt") as f:
            for host in f:

                result = re.match(r'(\w+)\-(.*)', host).groups()
                result = (list(result))  # 主机名和编号,将元组结果转列表
                result.reverse()  # 反转列表    account-98-1 -> 98-1.account
                domain = '.'.join(result)  # 拼接

                run(domain)

    else:
        print("DEBUG:\tTest")
        for host in hostlist:

            result = re.match(r'(\w+)\-(.*)', host).groups()
            result = (list(result))  # 主机名和编号,将元组结果转列表
            result.reverse()  # 反转列表
            domain = '.'.join(result)  # 拼接

            run(domain)

    pprint.pprint(results)
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018年11月1日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • telnetlib 远程telnet库 paramiko 远程ssh库
  • ssh批量按时备份网络设备配置
  • py2 telnet远程执行
  • ssh 批量远程执行例2
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档