Django + IIS + Python build Microsoft ad domain control API Management Center

osc_ kq4xzgbe 2020-11-12 12:55:01
django iis python build microsoft

This paper mainly introduces , How to use Django+IIS+Python Build an interface Center . Give Way ERP perhaps OA The system can go through API How to manage AD Domain control server . At the same time , have access to Django Call other Python Script , Realize more abundant functions
The example shown in this paper is an example of the actual landing scenario :
A user applies for database permission , Inside the enterprise ERP After the process approval is completed ,ERP The system directly calls the interface to send the employee AD Domain accounts join the database user group .
This paper mainly deals with the knowledge points :

1、IIS+Django Deploy
2、IIS Application processing module
3、Django Request processing logic
4、Django Call local Python Script and process the returned results
5、Python adopt os.system Call the command line to implement AD Domain controller management


One 、 Project overview

1、Django Introduction to the framework

About Django frame , There are other big articles on the Internet , In this article, I will make a few simple remarks
Portal :Django Framework introduction and configuration

Django, Pronunciation is [`dʒæŋɡəʊ], Go out and talk to people , Read as [ Dijiang dog ]

django Yes, it is python Open source for language writing web Development framework , And follow MVC Design .

Birth history : Lawrence publishing group to develop a news content based website , And developed this framework , On 2005 year 7 Month in BSD Issued under license . The name comes from Belgian jazz musicians DjangoReinhardt, He is a gypsy , Mainly playing guitar , I played violin and so on .

because Django The rapid development in recent years , More and more widely used , Be famous IT Development magazine SDTimes The selection of 2013SDTimes100, At the top of "API、 Libraries and frameworks " Classification No 6 position , Considered to be the best in the field .

django The frame is a web frame , And it's a back-end framework program , It's not a server , We need to pay attention to
django Frameworks help us encapsulate a lot of components , Help us to achieve various functions , It has strong expansibility .

2、 This example file structure

The code involved in this example has been uploaded Github
Project file structure :
./ApiSite The contents mainly involve Django Their own process
./api The contents are user-defined interface pages , Interface URL http://x.x.x.x/api
./log The directory is the log directory
./Python_Program The directory is a custom third party Python The directory where the script is stored
 Insert picture description here

Two 、 Environment installation and preparation

1、Windows+IIS+AD Microsoft Suite

In this example , because Windows Access control , We have to stay AD Run directly on the domain controller bat Orders can be right AD Resource management within the domain .

Therefore, our server must be deployed in one Windows Server , And the role of this server in the domain needs to be DC and GC, And it can be read-only Of DC or GC.

1.1 Windows The server

Suggested choice Server 2012 Above version , The specific system version should be consistent with other domain controller versions as much as possible . In this case, use Windows Server 2016

1.2 IIS The server

Because the operating system must be selected as Windows Server, So choose the one that matches the operating system version IIS that will do , In this case, use IIS 10.0
One thing in particular to note , This example must use Web The server > Application development >CGI function . In the deployment IIS Please make sure to check .
 Insert picture description here

1.3 Microsoft AD domain controller

Will be prepared for Windows Server The server joins the existing AD Domain , And set it to DC perhaps GC Role's domain controller .
If you finish reading this article , Discovery only needs Django+Python The function of , There is no need to manage AD Domain . Then this server can not add domain , You can even choose other front-end servers . such as CentOS+Django

2、Python Environmental installation

visit download Windows Version of Python, In this example, the latest Python 3.8 edition .

3、Python wfastcgi Depending on the environment to install

stay Windows Next , We can't use uwsgi, But we can use wfastcgi Replace it , open CMD window , Input command installation wfastcgi:

pip install wfastcgi

After successful installation , Start it with the following command :


 Insert picture description here
Pictured above , After successful startup , It will bring Python Path and wfastcgi The path is shown , We need to copy this path , Well preserved , It's good to use it later .


Be careful : The path above , By Python Path and interpreter “|” as well as “” File path composition .

3、Django Environmental installation]
Use the following command to install the latest version Django

pip install Django==3.0.8

4、PIP Dependent package installation

3、 ... and 、 Server configuration

1、IIS Configuration and fastCGI To configure

1.1 Add new website

open IIS Manager , Right click “ Website ”, Click on “ Add a website ”
here , We add a name called Django_API Website , The physical storage path is in C Of the root directory \Django_API Next .
 Insert picture description here
 Insert picture description here

1.2 Configure the handler map to use fastCGI

1.2.1 Using the graphical interface

Open the established website , choice “ Handler mapping ”, And then choose “ Add module mapping ”
 Insert picture description here ----------> Insert picture description here
 Insert picture description here
Configure according to the above figure , The first part of the executable file is python.exe The path of , Intermediate use “|” Division , The latter part is Path to file .
This information is in this article “ Two 、3、Python wfastcgi Depending on the environment to install ” I mentioned , function wfastcgi-enable start-up wfastcgi Then the path information given by the system .

1.2.2 Modify profile mode

Edit... In the root directory of the website web.conf file , Follow the example below to add ,name Field selection ,scriptProcessor Field in accordance with 1.2.1 Fill in as shown in

<?xml version="1.0" encoding="UTF-8"?>
<add name="Python FastCGI"
scriptProcessor="c:\users\administrator\appdata\local\programs\python\python38\python.exe|c:\users\administrator\appdata\local\programs\python\python38\lib\site-packages\" resourceType="Unspecified" requireAccess="Script" />

1.2.3 What is? fastCGI

fastCGI It's a kind of CGI,CGI( Universal gateway interface ) It's a program , Running on the server , Provide the same as the client HTML Interface to the page , Generally speaking CGI It's like a bridge , Combine web pages with WEB The executors in the server are connected , It is the HTML The received instructions are passed to the server , Then return the result of the server execution to HTML page ; use CGI You can process tables , Database query , Sending email and many other operations , The most common CGI The program is the counter .CGI Make the web page not static , It's interactive .
In this case , Front-end WEB The server is IIS,IIS The data we receive needs to be passed to Python.exe The program runs , So we choose fastCGI Module to connect IIS and Python.

1.3 fastCGI Set up

1.3.1 Global settings

Back to server , Click on “fastCGI Set up ”, Click on “ Add application ”
 Insert picture description here
 Insert picture description here

1.3.2 Website setup

Go back to the website , Click on “ Application settings ”
 Insert picture description here
Add the following three environment variables
 Insert picture description here

1.4 web.conf File examples

According to the above configuration ,IIS Will automatically update in the root directory web.conf file , If the above configuration is troublesome , Paste directly below web.conf File can

<?xml version="1.0" encoding="UTF-8"?>
<add name="Python FastCGI"
# Replace it with real python and wfastcgi route
<add key="WSGI_HANDLER" value="django.core.wsgi.get_wsgi_application()" />
<add key="PYTHONPATH" value="C:\API_site" /> # Replace it with a real website ROOT Catalog
<add key="DJANGO_SETTINGS_MODULE" value="ApiSite.settings" /> # Remember this ApiSite, You can use it later

1.5 Application identity settings

As shown in the figure below , Application pool -> Right click on the new project -> Advanced settings -> Process model features -> Built in account -> choice LocalSystem
This operation is to grant permissions to applications that can execute local programs , Otherwise, the application will not be able to call other local program files .
 Insert picture description here

1.6 web.conf Unlock

IIS7 Later versions have adopted more secure web.config Management mechanism , By default, the configuration item is locked and cannot be changed .
In this case , If it is not unlocked, direct access will report HTTP error 500.19 Internal Server Error
 Insert picture description here
open CMD, Enter the following two commands in turn :

%windir%\system32\inetsrv\appcmd unlock config -section:system.webServer/handlers
%windir%\system32\inetsrv\appcmd unlock config -section:system.webServer/modules

1.7 Copy File to the website root directory

take c:\users\administrator\appdata\local\programs\python\python38\lib\site-packages\ Copy to the root directory of the website
 Insert picture description here
at present , The above two files exist in the root directory of the website

2、Django To configure

thus , We just refresh the website , You should have seen , The program is trying to call the root directory of the website ApiSite modular .(“ 3、 ... and 、1.4 web.conf File examples ” The module name specified in )
 Insert picture description here
Next , We're going to start configuring Django, Let the previous configuration fastCGI You can successfully tune up Django

1、 structure ApiSite Catalog

This directory is Django Running directory
Create in the root directory of the website ApiSite Catalog , If you want to change it to another name , in front “ 3、 ... and 、1.4 web.conf File examples ” in , You can modify DJANGO_SETTINGS_MODULE Value of field .
The key documents in this directory are as follows : Log related , in DENUG The switch is True Call this file Main function entry , And it references urls and api Sub folder function Call the final application as a view Processing module Key configuration

# from django.contrib import admin
from django.urls import path
from api.views import get_data # Import view 
# here "api.views" Corresponding to the website root directory /api/ file 
urlpatterns = [
# path('admin/',,
path("api", get_data), # Define routes (url)
# here "api" Corresponding to the website root directory /api subdirectories Key configuration

'api.apps.ApiConfig', # load api application 
# here "api.apps" Corresponding to the website root directory /api/ file 

2、 structure api Catalog

This directory is the actual custom script run Directory
In this case , There are two necessary files in this directory Define the run Directory , This case Actually received data , Processing data , The program that returns data Key configuration

from django.apps import AppConfig
class ApiConfig(AppConfig):
name = 'api'
# Return the name of the directory Key configuration

from django.http.response import JsonResponse
def get_data(request):
return JsonResponse({"msg": " The excited heart , Shaking hand , The program is finally running "})

 Insert picture description here

Four 、 Request format and return format design

1、 Request format

In this case , We use POST Form transfer form
Use request.POST.get("par_name") Method to receive the value of the specified form field
In this case, the lock uses POST FORM Format standard


Field explanation
SECRET: Confidential fields , Fixed value , Randomly generate before deployment , And replace get_data(request): Medium sha256 Check value
hashlib.sha256(SECRET.encode()).hexdigest() != 'ae3e5f4098d40e38846f69bf83cf8f8c18a40fb27f9f7da2aa23f63241089a85'
API_POST_METHOD: Request method fields , Digital coding according to function release date +4 Serial number writing . Such as 202007020001 Express 2020 year 7 month 2 The first feature released today . The corresponding relation refers to “ Schedule 1 :API_POST_METHOD Field definition table ”
parameter: Parameter fields , according to “ Schedule 1 :API_POST_METHOD Field definition table ” Pass the parameters of the content .

2、 Returns the format

In this case, we return a json Format structure , It is used for the upper program to determine the call result .
For the call bat Method of execution , The return is python os.system() The return value of , Be right 0, Error for -2147024809.
For the call google,alicloud And so on , Pass on Google,alicloud Wait for the return value of the interface .
return JsonResponse({"msg": "%s"%run_result})

3、 Log format

Give an example of the log format of a correct request

15-07-2020 12:53:16:log:Request from IP:
15-07-2020 12:53:16:log:GET SECRET(sha256):ae3e5f4098d40e38846f69bf83cf8f8c18a40fb27f9f7da2aa23f63241089a85
15-07-2020 12:53:16:log:SECRET CHECK PERMIT
15-07-2020 12:53:16:log:GET API_POST_METHOD:202007111001
15-07-2020 12:53:17:log:sent_sms to_address:86***************,from_sign:Ω÷Ω«µÁ◊”,TemplateCode:SMS_108*******6,TemplateParam:{"name":"∂∫¿œ ¶","CNname":"*******","pass1":"***********","pass2":"************"}
15-07-2020 12:53:17:log:run_result:{"ResponseCode":"OK","NumberDetail":{"Country":"China","Region":"Beijing","Carrier":"China Unicom"},"ResponseDescription":"OK","Segments":"2","To":"86*************","MessageId":"1*********6982"}

Examples are given to illustrate the log format of several error requests

15-07-2020 12:56:22:log:Request from IP:
15-07-2020 12:56:22:log:GET SECRET(sha256):4a2aba321f57cab2057ced36fc0f0e8d0fee5256426d663271a575461a786355
15-07-2020 12:56:22:log:run_result:Invalid SECRET
15-07-2020 12:56:31:log:
15-07-2020 12:56:31:log:Request from IP:
15-07-2020 12:56:31:log:GET SECRET(sha256):ae3e5f4098d40e38846f69bf83cf8f8c18a40fb27f9f7da2aa23f63241089a85
15-07-2020 12:56:31:log:SECRET CHECK PERMIT
15-07-2020 12:56:31:log:run_result:API_POST_METHOD EMPTY
15-07-2020 12:56:38:log:
15-07-2020 12:56:38:log:Request from IP:
15-07-2020 12:56:38:log:GET SECRET(sha256):ae3e5f4098d40e38846f69bf83cf8f8c18a40fb27f9f7da2aa23f63241089a85
15-07-2020 12:56:38:log:SECRET CHECK PERMIT
15-07-2020 12:56:38:log:GET API_POST_METHOD:20191128000122
15-07-2020 12:56:38:log:run_result:Invalid API_POST_METHOD code

5、 ... and 、 Introduction to the main function points

1、Python call bat perform AD Domain control management related functions

Execute the process
structure dsmod Command template -&gt; Pass in the parameter -&gt; write in test.bat-&gt; function test.bat-&gt; obtain OS Running results -&gt; Write to the log -&gt; Return the run result
Found in actual test ,os.popen() Method execution dsmod On command , Facing the problem of insufficient authority , Unable to manage precontrol resources as Administrator .
So in this case, we use os.system() Method run bat Script . Unfortunately ,os.system() Method can not get the specific operation results of the system , You can only get whether the command is working properly .
Return value , Be right 0, Error for -2147024809

def run_bat():
#bat Execute function 
run_result = os.system("test.bat >> %s\log\API_run_log.txt"%IIS_SITE_DIR)
os.system("del test.bat")
except Exception as err:
return err
return run_result
class Microsoft_AD:
# Microsoft AD Domain related operations 
def Add_Database_User_Group(CNname):
# Add normal Database User permissions 
with open("test.bat", "w") as f:
# Create a new file in write mode , Write the command to be executed 
f.write("dsquery user -upn %[email protected] | dsmod group \"CN=Database_User_1,OU=Database,DC=al,DC=com\" -addmbr"%CNname)
#dsquery transformation UPN to CNname,dsmod Add group users 
except Exception as err:
return err
return run_result
def get_data(request):
name = request.POST.get("name")
# adopt request.POST.get() Method to get POST The form content in the request 
return JsonResponse({"msg": "%s"%run_result})

2、SECRET Confidential and API_POST_METHOD Method validation

In this case , There is no Django The authentication mechanism of . But to ensure the interface security , Adopted SECRET Confidential and METHOD Method verification mechanism to ensure the interface security to a certain extent .

if request.method != "POST": # Support only POST Method 
save_log("Receive WRONG request, not POST method")
return JsonResponse({"msg": "Receive WRONG request, not POST method"})
SECRET = request.POST.get("SECRET")
#sha256 After SECRET by :ae3e5f4098d40e38846f69bf83cf8f8c18a40fb27f9f7da2aa23f63241089a85
if SECRET==None: # check SECRET Whether the field exists , There is no direct return abnormal 
run_result='SECRET EMPTY'
return JsonResponse({"msg": "%s"%run_result})
save_log("GET SECRET(sha256):%s"%hashlib.sha256(SECRET.encode()).hexdigest())
if (hashlib.sha256(SECRET.encode()).hexdigest() != 'ae3e5f4098d40e38846f69bf83cf8f8c18a40fb27f9f7da2aa23f63241089a85'):
# check SECRET Whether the field is correct , Not right, direct return abnormal . remember , Here is the verification sha256 Post message 
run_result='Invalid SECRET'
return JsonResponse({"msg": "%s"%run_result})
if API_POST_METHOD==None: # check API_POST_METHOD Whether the field exists , There is no direct return abnormal 
return JsonResponse({"msg": "%s"%run_result})
run_result='Invalid API_POST_METHOD code'
if API_POST_METHOD=='201909230001':
name = request.POST.get("name")
# check API_POST_METHOD Whether the field is correct , If none of them matches ,run_result='Invalid API_POST_METHOD code'
except Exception as err:
return JsonResponse({"msg": "%s"%err})
return JsonResponse({"msg": "%s"%run_result})

For this code , Need to maintain one API_POST_METHOD Field definition table , After the deployment, the user , Maintain according to the actual situation .
 Insert picture description here

3、 When a new user is created, the existing user is retrieved in a loop , And give the user name +n

give an example , It already exists in the company [email protected] and [email protected] mailbox , If the name of the new employee is the same as zhangsan The nuptial , When creating users . The system will create a loop to retrieve existing users , establish [email protected] The mailbox of

def main(primaryEmail,mail_password,ad_password,familyName,givenName,orgUnitPath,PhoneNumber):
while get_user_info != "Resource Not Found: userKey":
if i != 0:
# Mailbox prefix step by step +1
if get_user_info == "Resource Not Found: userKey":
Google_APIrequest.add_user(credentials,primaryEmail,familyName,givenName,mail_password,orgUnitPath,PhoneNumber)# add to google mailbox 
Microsoft_AD.add_user(primaryEmail,familyName,givenName,ad_password,orgUnitPath,PhoneNumber)# add to AD Domain account 
#print(primaryEmail+" is a new user. Will add new user with this email")
#print(primaryEmail+" is already exist. Try next one.")
new_user_data={ 'primaryEmail' : get_new_user_info.get('primaryEmail'), 'givenName' : get_new_user_info.get('name').get('givenName'), 'familyName' : get_new_user_info.get('name').get('familyName'), 'orgUnitPath' : get_new_user_info.get('orgUnitPath'), 'recoveryPhone':get_new_user_info.get('recoveryPhone')}
json_new_user_data=json.dumps(new_user_data, sort_keys=True, indent=4, separators=(',', ': '), ensure_ascii=False)

4、Google Gsuit Interface call , management Google Admin All users in the domain

In this example Google Admin Of SDK call Google Of API Interface management domain users , Including user's new creation , Reset password , Pause mailbox , Leave, delete account, etc .
Please refer to 【 Tease the teacher to take you to learn IT】Google Admin Service account number +API management G suit All domain users in

5、SMS SMS Gateway Interface

In this case, we call the Ali cloud short message gateway to send a welcome message to the new employee , And when you reset the domain account password 【 Verification Code 】 SMS .
Alibaba cloud SMS How to use the gateway , See
SMS service > Development of guidelines ( new edition )>API overview

6、 ... and 、 Process test and interface call

Here is an example of an interface test script , It is suitable for testing various methods in the interface of this example . Users can modify according to the actual situation .

import json
import urllib
import requests
import sys
import datetime
import os
def test():
headers = {"Content-Type": "text/plain"}
'name':'[email protected]'
request ="",data=data)
except Exception as err:
raise err
return request.text
def main():
except Exception as err:
if __name__ == '__main__':

Run correctly , return msg as follows
 Insert picture description here
Print the log as follows :

15-07-2020 21:32:54:log:Request from IP:
15-07-2020 21:32:54:log:GET SECRET(sha256):ae3e5f4098d40e38846f69bf83cf8f8c18a40fb27f9f7da2aa23f63241089a85
15-07-2020 21:32:54:log:SECRET CHECK PERMIT
15-07-2020 21:32:54:log:GET API_POST_METHOD:201909230001
15-07-2020 21:32:54
C:\OA_API_site>dsquery user -upn | dsmod group "CN=Database_User_1,OU=Database,DC=csdn,DC=com" -addmbr
dsmod success :CN=Database_User_1,OU=Database,DC=al,DC=com
15-07-2020 21:32:54:log:run_result:0
本文为[osc_ kq4xzgbe]所创,转载请带上原文链接,感谢

  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database