问题描述
我正在研究一个用例,以通过PyAD在AD中创建组,并通过flask创建该文件夹的文件夹和组。
我正在使用for循环来传递参数和返回响应。如果该组存在,则不应创建代码,否则应创建代码,然后继续创建文件夹并设置权限。
但是对于第一个传入请求的组,逻辑适用,但是第二个并没有进入循环。
面对问题,使其无法通过烧瓶工作并处理响应。有没有办法做到这一点,请帮忙。
app = Flask(__name__)
api = Api(app)
#Class to create fileshare
class Test(Resource):
def post(self):
pythoncom.CoInitialize()
# Get JSON arguments from Payload shared NAS path,directorname groupname with read access and right access
parentdir = request.json.get("shareUNCPath")
dirname = request.json.get("shareFolderName")
readGroup = request.json.get("readGroup")
writeGroup = request.json.get("writeGroup")
domainName = request.json.get("domain")
groupList = [readGroup,writeGroup]
#for gn in groupList:
try:
j=(len(groupList))+1
if readGroup == writeGroup:
j=(len(groupList))-1
#for gn in len(groupList):
for i in range(4):
groupName = groupList[i]
pyad.set_defaults(username="username",password="password",ldap_server="ldapServer")
rGroup = adgroup.ADGroup.from_cn(groupName)
logging.debug("read group {} available in AD ".format(groupName))
if __name__ == "__main__":
os.makedirs(path)
igroup,domain,type = win32security.LookupAccountName (domainName,groupName)
sd = win32security.GetFileSecurity(path,win32security.DACL_Security_informatION)
dacl = sd.GetSecurityDescriptorDacl()
logging.debug("Domain1 {},Group1 {}".format(domainName,groupName))
if groupName in readGroup:
dacl.AddAccessAllowedAce(win32security.ACL_REVISION,con.GENERIC_READ,igroup)
if groupName in writeGroup:
dacl.AddAccessAllowedAce(win32security.ACL_REVISION,con.GENERIC_WRITE,igroup)
isdir = os.path.isdir(path)
if isdir == True:
sd.SetSecurityDescriptorDacl(1,dacl,0)
win32security.SetFileSecurity(path,win32security.DACL_Security_informatION,sd)
dacl = sd.GetSecurityDescriptorDacl()
cnt=dacl.GetAceCount()
for i in range(0,cnt):
rev,access,usersid = dacl.GetAce(i)
user,group,type = win32security.LookupAccountSid(domainName,usersid)
details = ('Group: {}/{}'.format(group,user),rev,access)))
resp = Response('Successfully created file share {}. Details {}'.format(dirname,details))
print (resp)
resp.status_code = 200
return resp
except Exception as e:
errormsg = str(e)
print (errormsg)
if "The server is not operational" in errormsg:
resp = Response('AD operation Failed,unable to connect to Active Directory. Error - {}'.format(e))
print (resp)
resp.status_code = 301
return resp
else:
try:
for i in range(4):
groupName = groupList[i]
pyad.set_defaults(username="username",password="pasword",ldap_server="ldapServer")
ou = pyad.adcontainer.ADContainer.from_dn(group_OU)
rGroup = adgroup.ADGroup.create(
name=groupName,security_enabled = True,scope=groupScope,container_object=ou,optional_attributes={"description": description}
)
if rGroup.displayname == (groupName):
if __name__ == "__main__":
os.makedirs(path)
#groupr = win32security.LookupAccountName ("",readGroup)
a.logon()
time.sleep(5)
igroup,groupName)
sd = win32security.GetFileSecurity(path,win32security.DACL_Security_informatION)
#dacl = win32security.ACL()
dacl = sd.GetSecurityDescriptorDacl()
#acl = pywintypes.ACL()
#set permessions for readGroup with GENERIC_READ level permessions
#dacl.AddAccessAllowedAce(win32security.ACL_REVISION,groupr)
if groupName in readGroup:
dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION,con.OBJECT_INHERIT_ACE|con.CONTAINER_INHERIT_ACE,con.GENERIC_READ|con.GENERIC_EXECUTE,igroup)
if groupName in writeGroup:
dacl.AddAccessAllowedAce(win32security.ACL_REVISION,igroup)
isdir = os.path.isdir(path)
if isdir == True:
sd.SetSecurityDescriptorDacl(1,0)
win32security.SetFileSecurity(path,sd)
dacl = sd.GetSecurityDescriptorDacl()
cnt=dacl.GetAceCount()
for i in range(0,cnt):
rev,usersid = dacl.GetAce(i)
user,usersid)
details = ('Group: {}/{}'.format(group,access)
#return ("Success Fileshare created: {} ".format(dirname))
resp = Response('Successfully created file share {}. Details {}'.format(dirname,details))
print (resp)
resp.status_code = 200
return resp
except Exception as e:
print(e)
resp = Response('AD operation Failed,unable to create to group {}. Error - {}'.format(groupName,e))
print (resp)
resp.status_code = 302
return resp
api.add_resource(Test,'/test')
if __name__ == "__main__":
#context = ('local.crt','local.key')#certificate and key files
app.run(port="7050",host="0.0.0.0",use_reloader=True)
解决方法
我检查了您的代码。有两件事应该改变。
- 您将
i
用作外部和内部循环的循环变量 - 在第一个循环中,使用异常触发组创建。这将退出循环,不再处理任何组。您应该在
range(4)
循环内移动异常块。
这是带注释的代码。
class Test(Resource):
def post(self):
.......
try:
..........
for i in range(4): # using i as loop variable,loop will exit if exception
........
if __ name __ == "__ main __": # if group exists,update permissions,throws exception if group does not exist
........
if isdir == True:
........
for i in range(0,cnt): # using i as loop variable,again
.........
# here is the problem - if the first group does not exist,an exception is thrown and the other groups are not processed
except Exception as e: # group does not exist,must add # You should move this inside the for loop
............
try:
for i in range(4): # using i as loop variable
...........
if rGroup.Displayname == (groupName):
if __ name __ == "__main__":
.........
if isdir == True:
........
for i in range(0,again
..........
为澄清起见,总体逻辑应如下所示:
for i in range(4): # each group
try:
# update permissions
except Exception as e:
# add new group
作为旁注,请尝试在不使用try \ except块的情况下检查该组是否存在。正常程序流程中不应使用异常。