django小项目,使用paramiko自动备份网络设备配置

 原来公司开发团队人员众多,有专门对接运维需求的开发人员,现在想要实现些功能可(只)以(能)自己写了-_- |   周末在家无事,用django搞个简单的功能练练手

django安装,配置

sudo pip3 install dgango
django-admin startproject mysite
django-admin startapp ssh
#models配置

class user(models.Model):
    user = models.CharField(max_length=64)
    passwd = models.CharField(max_length=64)

#setting配置

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'ssh'
]

import os
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR,'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(BASE_DIR,"statics"),
)

前端页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>backup</title>
    <style>
        *{margin: 0;}
        .top{background-color: whitesmoke; height: 52px;}
        .top-left{width: 402px;height: 53px;float: left;}
        .top-right{background-color: rgb(83, 83, 236);height: 53px;position:absolute;left:402px ;right: 0;}
        .left{background-color: whitesmoke;height: 800px;position:absolute;top: 53px; left: 1px;width: 400px;border: 1px solid;border-color: teal;}
        .right{background-color: whitesmoke;position:absolute;left: 403px;right: 0; top: 53px;white-space: pre;height: 800px;overflow: auto;}
        .devices{margin-top: 7px;}
        .devices:hover{cursor: pointer;}
        .back:hover{background-color: teal; cursor: pointer;}
        .pop{margin-left: 50px;margin-top: 10px;}
        .pop:hover{cursor: pointer;}
        .hidden{display: none;}
        .site{margin-left: 10px;}
        .img{ display: block;height:50px; width:50px; float: right;margin-right: 8px;color: white;border-radius: 30px;text-align: center;line-height: 53px;}
    </style>
    <script src="/static/jquery-3.6.0.js"></script>

</head>
<body>
    <div class="top">
        <div class="top-left">
            <h3 style="text-align: center; line-height: 52px;">配置备份</h3>
        </div>
        <div class="top-right">
            <p class='img'>dark</p>
            <img class='img' src="/static/dark.jpg">
        </div>
    </div>
    <div class="left">
      
                <div class="zz pop" >
                <p class="button">郑州pop</p>
                <form class="hidden site" action="/backup/" method="POST">
                    <p><input type="checkbox" value="1-10.0.3.101" name="host">juniper </p>
                    <p><input type="checkbox" value="2-10.0.3.102" name="host1">cisco</p>
                    <input class="back" type='submit' value="submit">
                    {%csrf_token%}
                </form>
                </div>
                <div class="FS pop" >
                    <p class="button">广州pop</p>
                    <form class="hidden site" action="/backup/" method="POST">
                        <p><input type="checkbox" value="10.0.3.101" name="host">juniper </p>
                        <p><input type="checkbox" value="10.0.3.102" name="host">cisco</p>
                        <input class="back" type='submit' value="submit">
                        {%csrf_token%}
                </form>
                </div>
                <div class="FS pop" >
                    <p class="button">北京pop</p>
                    <form class="hidden site" action="/backup/" method="POST">
                        <p><input type="checkbox" value="10.0.3.101" name="host">juniper </p>
                        <p><input type="checkbox" value="10.0.3.102" name="host">cisco</p>
                        <input class="back" type='submit' value="submit">
                        {%csrf_token%}
                </form>
                </div>
                <div class="FS pop" >
                    <p class="button">上海pop</p>
                    <form class="hidden site" action="/backup/" method="POST">
                        <p><input type="checkbox" value="10.0.3.101" name="host">juniper </p>
                        <p><input type="checkbox" value="10.0.3.102" name="host">cisco</p>
                        <input class="back" type='submit' value="submit">
                        {%csrf_token%}
                </form>
                </div>
                <div class="FS pop" >
                    <p class="button">深圳pop</p>
                    <form class="hidden site" action="/backup/" method="POST">
                        <p><input type="checkbox" value="10.0.3.101" name="host">juniper </p>
                        <p><input type="checkbox" value="10.0.3.102" name="host">cisco</p>
                        <input class="back" type='submit' value="submit">
                        {%csrf_token%}
                </form>
                </div>
                <div class="FS pop" >
                    <p class="button">青岛pop</p>
                    <form class="hidden site" action="/backup/" method="POST">
                        <p><input type="checkbox" value="10.0.3.101" name="host">juniper </p>
                        <p><input type="checkbox" value="10.0.3.102" name="host">cisco</p>
                        <input class="back" type='submit' value="submit">
                        {%csrf_token%}
                </form>
                </div>
                <div class="FS pop" >
                    <p class="button">海外pop</p>
                    <form class="hidden site" action="/backup/" method="POST">
                        <p><input type="checkbox" value="10.0.3.101" name="host">juniper </p>
                        <p><input type="checkbox" value="10.0.3.102" name="host">cisco</p>
                        <input class="back" type='submit' value="submit">
                        {%csrf_token%}
                </form>
                </div>
        </div>
    </div>
    <div class="right">
        {{show}}
    </div>

    <script>
        $('.pop .button').click(function(){
            $(this).siblings().slideToggle()
        })

    </script>

</body>
</html>

url路由

urlpatterns = [
    path('admin/', admin.site.urls),
    path('menu/', menu.menu),
    path('backup/', menu.backup),
    path('login/', menu.login),
]

后端代码

import paramiko,time,datetime
from ssh import models


#SSH功能
def Testsshcon(ip,port,username,key):
    try:
        sshcon=paramiko.SSHClient()
        sshcon.set_missing_host_key_policy(paramiko.AutoAddPolicy())
#判断不同设备型号,执行不同命令
        if ip[0]=="1":
            cmds=['show conf | dis set | no-more\n','\n']
            ip = ip[2:]        
        if ip[0]=="2":
            cmds=['terminal length 0\n','show run\n']
            ip = ip[2:]
        sshcon.connect(ip,port,username,key,compress=True)
        conn=sshcon.invoke_shell()
        res = ''
        for cmd in cmds:
            time.sleep(1)
            conn.send(cmd)
            time.sleep(1.3)
            out=conn.recv(100000)
            res += out.decode('utf-8')
        return(res)
        sshcon.close()
    except Exception as e:
        return ("connet error",e)#接收前端POST内容,调用ssh函数,返回处理后页面
def backup(request):
  html_show = '配置文件'
  if request.method == 'POST':
      private_key = paramiko.RSAKey.from_private_key_file('/home/dark/.ssh/id_rsa')
      host = request.POST.dict()
    del host['csrfmiddlewaretoken'] 
      html_show = ''
#多选备份功能
      for x in host:
          res = Testsshcon(host[x],22,'dark2',private_key)
#写入备份文件
          file = '/home/dark/backup/'+ datetime.datetime.now().strftime("%Y-%m-%d")+'-'+host[x]
          with open(file,'w') as a:
              a.write(res)
          html_show +=res
    return render(request,'backup.html',{'show':html_show})

#登录验证使用
def login(request):
    tip = '用户名或密码错误'
    if request.method == 'POST':
        user = request.POST.get('username',None)
        user_passwd = request.POST.get('passwd',None)
        print(user,user_passwd)
        userinfo=models.user.objects.get(user=user)
        passwd = userinfo.passwd
        if user_passwd == passwd:
            return redirect('/backup')
        else:
            return render(request,'login.html',{'passwd':tip})
    return render(request,'login.html')

最终页面效果

Leave a Reply

Your email address will not be published. Required fields are marked *

X