passport 自动取密码

django settings.py

"""
Django settings for password project.

Generated by 'django-admin startproject' using Django 1.9.5.

For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'twc7jzj(@kgl(jaa6hhy1y1!z(b75_ex^=76a(b6j1u76d3=h!'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

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

MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    #'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'password.urls'

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',
            ],
        },
    },
]

WSGI_APPLICATION = 'password.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases

DATABASES = {
    'default': {
    'ENGINE': 'django.db.backends.mysql',
    'NAME':'fengjian',
    'USER': 'fengjian',
    'PASSWORD': '123456',
    'HOST': '127.0.0.1',
    'PORT': '3306',
    }
}


# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/

STATIC_URL = '/static/'


SESSION_COOKIE_AGE = 600

urls.py

"""password URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url,include
from django.contrib import admin


urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^app01/',include('app01.urls')),

]

passpor document

models.py

from __future__ import unicode_literals

from django.db import models

# Create your models here.

class UserType(models.Model):
    name = models.CharField(max_length=60)

class User(models.Model):
    username = models.CharField(max_length=60)
    password = models.CharField(max_length=60)
    user_type = models.ForeignKey('UserType')

class UserGroup(models.Model):
    groupname = models.CharField(max_length=60)
    user_group = models.ManyToManyField('User')

class Asset(models.Model):
    hostname = models.CharField(max_length=60)
    ip = models.GenericIPAddressField()
    asset_usergroup = models.ForeignKey('UserGroup')

vim paramiko_modle.py

#!/usr/bin/env python
#-*- coding:utf-8 -*-

import paramiko

def paramiko_command(ipaddr,username,timeout=10):

    private_key_path = '/root/.ssh/id_rsa'

    key = paramiko.RSAKey.from_private_key_file(private_key_path)

    ssh = paramiko.SSHClient()

    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    ssh.connect(ipaddr,22,username,pkey=key)

    stdin, stdout, stderr = ssh.exec_command('/usr/bin/mkpasswd %s' %username)

    return stdout.read().strip()

    ssh.close();


paramiko_command('192.168.99.131','root')

urls.py

"""password URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url,include
from django.contrib import admin
import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^login/',views.login),
    url(r'^index/',views.index),
    url(r'^delete/',views.delete),
]

views.py

from django.shortcuts import render,render_to_response,redirect,HttpResponse
import models
import paramiko_modle
# Create your views here.

def login(request):
    ret = {'status':""}
    if request.method == 'POST':
        username = request.POST.get('username',None)
        print username
        password= request.POST.get('password',None)

        is_empty = all([username,password])

        print is_empty
        if is_empty:

            request.session['is_ssession'] = {'username':username}

            userobj = models.User.objects.filter(username=username,password=password)
            print userobj

            if userobj:

                return redirect('/app01/index/')

            else:
                ret['status'] = 'username or password input error'
        else:
            ret['status'] = 'Input is not empty'


    return render_to_response('login.html',ret)


def index(request):

    ret = {'status':"",
           'data':"",
           'session':"",
           'user':"",
           'ipaddr':"",
    }
    ssesiondict = request.session.get('is_ssession',None)

    if not ssesiondict:
        return  redirect('/app01/login/')
    else:
        if request.method == 'POST':

            username = request.POST.get('username',None)
            ip = request.POST.get('ip',None)

            is_empty = all({username,ip})

            if is_empty:
                result = paramiko_modle.paramiko_command(ip,username)
                ret['data'] = result
                ret['session'] = ssesiondict['username']
                ret['user'] = username
                ret['ipaddr'] = ip
            else:
                ret['status'] = 'username or ip is not empty'

    return  render_to_response('index.html',ret)

def delete(request):
    del request.session['is_ssession']
    return  redirect('/app01/login/')

templates   index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h5>index page  loginusername:{{ session }} </h5>
    <h3><a href="/app01/delete/"> logout </a></h3>

    <form action="/app01/index/" method="POST">
        <table>
            <tr>
                <td>username</td>
                <td><input type="text" name="username" value="{{ user }}" /></td>
            </tr>
            <tr>
                <td>IP</td>
                <td><input type="text" name="ip" value="{{ ipaddr }}" /></td>
            </tr>
            <tr>
                <td>password</td>
                <td><input  type="text" name="password" value="{{ data }}"  /></td>
            </tr>
            <tr>
                <td colspan="2" align="center"><input type="submit" value="commit" /><span>{{ status }}</span></td>
            </tr>
        </table>
    </form>
</body>
</html>

login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form method="POST" action="/app01/login/">
    <p>username:<input type="text" name="username" placeholder="username" /></p>
    <p>password:<input type="text" name="password" placeholder="passpwrd" /></p>
    <input type="submit" value="commit" />
    <label style="color: red">{{ status }}</label>
</form>
</body>
</html>
原文地址:https://www.cnblogs.com/fengjian2016/p/5369117.html