
    %
iL                        d Z ddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
mZ ddlT ddlmZ dadag ZdaddlZeZ	 	 	 	 	 	 	 d%d	Zd&d
Z	 d'dZd Zd Zd Z G d d          ZefdZd Zd Zd Zd Z d Z!d Z"d Z#defdefde fde!fde"fde#ffZ$ G d  d!ej%                  Z&d" Z'e(d#k    r$	  e'             dS # e)$ r  e*d$           Y dS w xY wdS )(a  A re-implementation of the MS DirectoryService samples related to services.

* Adds and removes an ActiveDirectory "Service Connection Point",
  including managing the security on the object.
* Creates and registers Service Principal Names.
* Changes the username for a domain user.

Some of these functions are likely to become move to a module - but there
is also a little command-line-interface to try these functions out.

For example:

scp.py --account-name=domain\user --service-class=PythonScpTest \
       --keyword=foo --keyword=bar --binding-string=bind_info \
       ScpCreate SpnCreate SpnRegister

would:
* Attempt to delete a Service Connection Point for the service class
  'PythonScpTest'
* Attempt to create a Service Connection Point for that class, with 2
  keywords and a binding string of 'bind_info'
* Create a Service Principal Name for the service and register it

to undo those changes, you could execute:

scp.py --account-name=domain\user --service-class=PythonScpTest \
       SpnCreate SpnUnregister ScpDelete

which will:
* Create a SPN
* Unregister that SPN from the Active Directory.
* Delete the Service Connection Point

Executing with --test will create and remove one of everything.
    N)adsi)*)Dispatch   serviceConnectionPointAc	           
      b   |p|}|st          j        t          j                  }|t          j        t          j                  }t          j        d|z   t          j                  }	|pg }dt          t          |ffdt          t          |ffdt          t          |fdt          t          |ffdt          t          |ffdt          t          |ffdt          t          | ffg}
|	                    d	|z   |
          }t                              d
|           t          |          }t          ||           |S )NLDAP://cnobjectClasskeywordsserviceDnsNameserviceDnsNameTypeserviceClassNameserviceBindingInformationcn=zNew connection point is at %s)win32apiGetComputerNameExwin32conComputerNameDnsFullyQualifiedGetComputerObjectNameNameFullyQualifiedDNr   ADsGetObjectIID_IDirectoryObjectADS_ATTR_UPDATEADSTYPE_CASE_IGNORE_STRINGCreateDSObjectloggerinfor   AllowAccessToScpProperties)service_binding_infoservice_class_nameaccount_namecontainer_namer   object_classdns_name_typedndns_namecompattrsnews               C:\Users\Dell Inspiron 16\Desktop\tws\AgrotaPowerBi\back-agrota-powerbi\mcp-client-agrota\venv\Lib\site-packages\win32comext/adsi/demos/scp.py	ScpCreater-   ?   s>    $9'9N V-h.TUU	z+H,IJJ Y^T-FGGD ~2H 
 :^<MN	)Cl_U	_&@(K	?,FT &		
 &!		
 (&!#		
#E0 

en4e
<
<C
KK/@@@
3--C|S111J    c                 (   |t          j        t          j                  }t                              d| |           t          j        d|z   t          j                  }|	                    d| z              t          
                    d|            d S )Nz&Removing connection point '%s' from %sr
   r   z%Deleted service connection point '%s')r   r   r   r   r   debugr   r   r   DeleteDSObjectr   )r$   r'   r)   s      r,   	ScpDeleter2   y   s    	z+H,IJJ
LL9>2NNN Y^T-FGGD.///
KK7HHHHHr.   z&{28630eb8-41d5-11d1-a9c1-0000f80367c1}z&{b7b1311c-b82e-11d0-afee-0000f80367c1}c                    | r| }nt          j        t          j                  }d}t	          ||          }|j        }|D ]q}t          t          j                  }t          t          z  |_        ||_        t          |_        d|_        t           |_        ||_        |                    |           r||_        t)          |||           |                                 t,                              d|           d S )NnTSecurityDescriptorr   z%Set security on object for account %r)r   r   r   NameSamCompatiblegetattrDiscretionaryAclr   r   CLSID_AccessControlEntryADS_RIGHT_DS_READ_PROPADS_RIGHT_DS_WRITE_PROP
AccessMaskTrustee!ADS_ACETYPE_ACCESS_ALLOWED_OBJECTAceTypeAceFlagsADS_FLAG_OBJECT_TYPE_PRESENTFlags
ObjectTypeAddAcesetattrSetInfor   r   )	
accountSAM	scpObjectschemaIDGUIDstrustee	attributesdaclsguidaces	            r,   r    r       s      M 01KLL 'I	I	&	&B

C  t455 02II  8  1	  	

3 BIy"%%%
KK7AAAAAr.   c                    t          |t                    st          |d          sJ d|z              t          j        t          j                  }|                    dd          d         }| st          j        t          j	                  } t                              d|            t          j        |t          j        t          j        z  t          j        z            }t          j        |d                   }t                              d	           t          j        ||| |           |                                 d S )
N__iter__z+spns must be a sequence of strings (got %r)\r   r   zSpnRegister using DN '%s')
domainNameflagsDomainControllerNamezDsWriteAccountSpn with spns %s)
isinstancestrhasattrr   GetUserNameExr6   splitr   r   r   r   r0   win32securityDsGetDcNamedsconDS_IS_FLAT_NAMEDS_RETURN_DNS_NAMEDS_DIRECTORY_SERVICE_REQUIREDDsBindDsWriteAccountSpnClose)serviceAcctDNspns	operationsamNamer   handles         r,   SpnRegisterri      s8   
 $$$ z)B)B  5< B
 $X%?@@GmmD!$$Q'G V 6x7TUU
LL,m<<< $#

"#

-.  D !$'=">??F LL1222#	   LLNNNNNr.   c                 x    d| z   }t          j        |t           j                  }|                    |           d S )Nr
   )r   r   IID_IADsUserSetPassword)username_dnnew_passwordaccountPathusers       r,   UserChangePasswordrq     s?     k)K[$*;<<D 	\"""""r.   c                 D    t           | k    rt          ||z             d S d S N)verboseprint)levelmsgargss      r,   logry     s-    %cDj r.   c                       e Zd ZdS )
_NoDefaultN)__name__
__module____qualname__ r.   r,   r{   r{     s        Dr.   r{   c                     | \  }}t          |||          }|s!|t          u r|                    d|z             |s|}|S )Nz4The '%s' option must be specified for this operation)r7   r{   error)poopt_namedefaultparseroptionsrets         r,   _get_optionr     sY    OFG
'8W
-
-C X7j((KhVWWW Jr.   c                 @    | d         }|                     |           d S )Nr   )r   )r   whyr   s      r,   _option_errorr      s#    UF
LLr.   c           
          t          t          | d          t          | d          t          | dd          t          | dd                    }|a|j        S )z!Create a Service Connection Pointbinding_stringservice_classaccount_name_samNr   )r   )r-   r   g_createdSCPdistinguishedName)r   scps     r,   do_ScpCreater   %  sb     B())B((B*D11RT22	  C L  r.   c                     t          | d          }	 t          |           nD# t          j        $ r2}|d         t          j        k    r t          dd|           Y d}~nd}~ww xY w|S )z!Delete a Service Connection Pointr   r      z@ScpDelete ignoring ERROR_DS_OBJ_NOT_FOUND for service-class '%s'N)r   r2   r   r   winerrorERROR_DS_OBJ_NOT_FOUNDry   )r   scdetailss      r,   do_ScpDeleter   2  s    	R	)	)BW": W W W1:888AQSUVVVVVVVVW Is   " A#(AA#c           
      2   t           t          | d           t          j        t          j        t          | d          t           j        t          | dd          dd          }|d         }t          dd|           |a	t                              |           |S )zCreate a Service Principal NameNz3ScpCreate must have been specified before SpnCreater   portr   r   zCreated SPN: %s)r   r   r[   DsGetSpnr]   DS_SPN_SERVICEr   r   ry   g_createdSPNLastg_createdSPNsappend)r   re   spns      r,   do_SpnCreater   >  s     bOPPP!B((&B"" D q'Cc"""Jr.   c                     t           st          | d           t          t          | dd          t           ft          j                   t           S )z4Register a previously created Service Principal Namez(SpnCreate must appear before SpnRegisteraccount_name_dnN)r   r   ri   r   r]   DS_SPN_ADD_SPN_OPr   s    r,   do_SpnRegisterr   U  sR     FbDEEEB)400	  
 r.   c                     t           st          | d           t          t          | dd          t           ft          j                   t           S )z6Unregister a previously created Service Principal Namez*SpnCreate must appear before SpnUnregisterr   N)r   r   ri   r   r]   DS_SPN_DELETE_SPN_OPr   s    r,   do_SpnUnregisterr   b  sR     HbFGGGB)400	"  
 r.   c                 ^    t          t          | d          t          | d                     dS )z(Change the password for a specified userr   passwordzPassword changed OK)rq   r   r   s    r,   do_UserChangePasswordr   n  s-    {2'899;r:;V;VWWW  r.   r-   r2   	SpnCreateri   SpnUnregisterrq   c                       e Zd Zd ZdS )HelpFormatterc                     |S rs   r   )selfdescriptions     r,   format_descriptionz HelpFormatter.format_description  s    r.   N)r|   r}   r~   r   r   r.   r,   r   r   ~  s#            r.   r   c                  j   i } g }t           D ]e\  }}d                    t          j        |j        d                    }|                    d| d|            || |                                <   ft          dz   d                    |          z   dz   }t          j        d|t                                }|
                    d	d
ddd           |
                    dddd           |
                    dddd           |
                    dddd           |
                    ddd           |
                    dddd            |
                    dd!d"           |
                    dd#d$           |
                    dd%d&           |
                    dd'd(d)d*+           |
                    dd,d-t          t          j                  .           |                                \  }}||f}		 t          |j                  |_        n,# t"          t$          f$ r |                    d/           Y nw xY w	 t          |j                  }
n# t"          t$          f$ rp 	 t          t+          t          |j                                                            }
n2# t$          t"          t.          f$ r |                    d0           Y nw xY wY nw xY w	 t0          j        }n(# t.          $ r t          j                    j        }Y nw xY w ||
           |j        r|j        r|                    d1           |j        r|xj        dz  c_        |j        a|j        r|r|                    d2           d3}t=          dd4|           |                                }|j         sd5|_         t=          d6d7|j                    |j!        s/d8                                |_!        t=          d6d9|j!                   |j"        sd:|_"        t=          d6d;|j"                   |s|                    d<           |D ]0}|                                | vr|                    d=|z             1|j#        rt=          d6d>|j#                   tI          j%        |j#        tL          j'        tL          j(                  |_)        t=          d6d?|j)                   tI          j%        |j#        tL          j'        tL          j*                  |_+        t=          d6d@|j+                   |D ]}| |                                         }||                    dA|z             d }	 	 t=          d6dB|            ||	          }t=          ddC||           n/#  |j,        r"t[          dD           t]          j/                      xY wne# t`          j        $ r/}|j1        \  }}}}|r	|d6         }nd}|}|r|dE|z   z  }Y d }~n,d }~wtL          j        $ r}|j1        \  }}}|}Y d }~nd }~ww xY w|rt=          ddF||           d S )GN
z        )subsequent_indentz  z: z
commands:
z%prog [options] command ...)usager   	formatterz-vcountrt   r   z)increase the verbosity of status messages)actiondestr   helpz-qz--quiet
store_truezDon't print any status messages)r   r   z-tz--testzGExecute a mini-test suite, providing defaults for most options and args z--show-tracebacksz&Show the tracebacks for any exceptionsz--service-classzThe service class name to use)r   z--portr   z)The port number to associate with the SPN)r   r   z--binding-stringz*The binding string to use for SCP creationz--account-namez0The account name to use (default is LocalSystem)z
--passwordzThe password to set.z	--keywordr   r   z[A keyword to add to the SCP.  May be specified
                              multiple times)r   r   r   z--log-levelz`The log-level to use - may be a number or a logging
                             module constant)r   r   z--port must be numericzInvalid --log-level valuez#Can't specify --quiet and --verbosezCan't specify args with --testzAScpDelete ScpCreate SpnCreate SpnRegister SpnUnregister ScpDeletez!--test - pretending args are:
 %sPythonScpTestr   z--test: --service-class=%szPython Poweredz--test: --keyword=%sztest binding stringz--test: --binding-string=%sz4No command specified (use --help for valid commands)z4Invalid command '%s' (use --help for valid commands)zTranslating account name '%s'zNameSamCompatible is '%s'zNameFullyQualifiedDNis '%s'zInvalid command '%s'zExecuting '%s'...z%s: %sz/--show-tracebacks specified - dumping exceptionz
	zCommand '%s' failed: %s)2handlersjointextwrapwrap__doc__r   loweroptparseOptionParserr   
add_optionrW   loggingWARNING
parse_argsintr   	TypeError
ValueErrorr   	log_levelr7   upperAttributeErrorr   setLevel	getLoggerquietrt   testry   rZ   r   r   r   r#   r[   TranslateNamer   NameUnknownr6   r   r   r   show_tracebacksru   	traceback	print_excr   rx   )_handlers_dict	arg_descsargfunc	this_descr   r   r   rx   r   r   slhandlererr_msgresultxxx_todo_changemehrdescexcargerr
extra_descxxx_todo_changeme1rw   s                          r,   mainr     s   NI + +	TIIhmDLGTTTUU	0c00Y00111&*syy{{##O+dii	.B.BBTIK"+//  F 8     i3T     V	     
5	     b+2QRRR

Ha&Q     
%Q     
#U     b,-CDDD

0     
0GO$$     %%''MGT
'	B/7<((z" / / /-...../6)**		z" 6 6 6	6GGW->-D-D-F-FGGHHIII~6 	6 	6 	6LL455555	66
*_ * * *  )* ByMMM} < <:;;;} 1oG| J 	;LL9:::RA3T:::zz||$ 	H$3G!/1FGGG 	=/5577G)7+;<<<% 	J%:G"0'2HIII  MKLLL W W99;;n,,LLORUUVVV  	GA.0DEEE#0#> ("68R$
 $
  	A*G,DEEE"/"= ("68U#
 #
 	A,g.EFFF  < < -?LL/#5666	A*C000 Axf----* *KLLL'))) . z 	/ 	/ 	/&7&<#RsF   V


G /6J..~ 	 	 	05ORsGGGGGG	  	<,c7;;;9< <s   <H &H?>H?I K*9J$#K$,KKKKKK* *"LL.VV8,V44V88X%W11XXX__main__z*** Interrupted)NNNr   r   NNrs   )r3   )+r   r   r   r   ntsecurityconr]   r   r   r[   r   win32com.adsir   win32com.adsi.adsiconwin32com.clientr   rt   r   r   r   r   r   r-   r2   r    ri   rq   ry   r{   r   r   r   r   r   r   r   r   r   IndentedHelpFormatterr   r   r|   KeyboardInterruptru   r   r.   r,   <module>r      s  " "H                        # # # # $ $ $ $ $ $
  	 )7 7 7 7tI I I I>5B 5B 5B 5BH& & &R# # #  
	 	 	 	 	 	 	 	 '1      

! 
! 
!	 	 	  .
 
 
	 	 	! ! ! ,,,N#&'01    H2   
k< k< k<\ z! ! ! !      ! s   6
C CC