¿Reconoces esto?<\/P>
<\/P>
Vamos a usar la ArcGIS API para Python con groups.search()<\/STRONG> y users.search()<\/STRONG> para obtener una visión general de nuestra organización. Luego compilamos una matriz - usuarios a lo largo del eje y y grupos a lo largo del eje x<\/EM> - con un 1 o un 0 para indicar si el usuario es miembro del grupo o no. Esta matriz se escribe en un archivo CSV.<\/P><\/P>Y entonces el jefe debería poder importar este CSV en una hoja de cálculo colorida y manejable. Con o sin un poco de ayuda.<\/P><\/P>¿Funciona el script a continuación para ti? Solo 'me gusta' o 'compartir' si es así. Y si quieres, puedes abrir tu Jupyter Notebook para probarlo línea por línea.<\/P><\/P>## ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++<\/SPAN>## Información de Gestión de ArcGIS Online<\/SPAN>## Script: agol_group_membership.py<\/SPAN>## Objetivo: crear una visión general de la membresía de grupos en tu organización ArcGIS Online<\/SPAN>## Autor: Egge-Jan Polle - Tensing GIS Consultancy<\/SPAN>## Fecha: 3 de agosto de 2018<\/SPAN>## ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++<\/SPAN>#<\/SPAN># Este script debe ejecutarse dentro de un entorno específico ArcGIS/Python usando el archivo batch abajo<\/SPAN># (Este archivo batch viene con la instalación de ArcGIS Pro)<\/SPAN># "C:\Program Files\ArcGIS\Pro\bin\Python\scripts\propy.bat" agol_group_membership.py<\/SPAN>#<\/SPAN>import<\/SPAN> csv, <\/span>os, <\/span> sysfrom arcgis.gis import GISfrom provide_credentials import provide_credentialsprint('===================')print('El script que se está ejecutando: ' + __file__)print('Primero debes iniciar sesión en ArcGIS Online')# Iniciar sesión<\/span>username, password = provide_credentials()my_agol = GIS("https://www.arcgis.com", username, password)print("Inicio: " + datetime.datetime.today().strftime('%c'))## Obtener todos los grupos<\/span>my_groups = my_agol.groups.search()## Opcionalmente: echar un vistazo a todos los grupos<\/span>#my_groups## Opcionalmente: contar el número de grupos<\/span>#len(my_groups)## Obtener todos los usuarios<\/span>my_users = my_agol.users.search(max_users = 350) # El valor predeterminado max_users = 100, así que aumentalo si tienes más## Opcionalmente: echar un vistazo a todos los usuarios<\/span>#my_users## Opcionalmente: contar el número de usuarios<\/span>#len(my_users)## Crear una lista con todos los títulos de grupo<\/span>my_group_titles = []for my_group in my_groups: my_group_titles.append(my_group.title)## Crear una lista con nombres de campos<\/span>fieldnames = []fieldnames = ['USERNAME','EMAIL']for title in my_group_titles: fieldnames.append(title)## Opcionalmente: echar un vistazo a los nombres de campos<\/span>#fieldnames## Crear un archivo CSV con una matriz de los grupos con sus miembros<\/span>today = datetime.datetime.today().strftime('%Y%m%d')fname = 'AGOL_Group_Membership' + today + '.csv'try: os.remove(fname)except OSError:passoutfile = open(fname, 'a')writer = csv.DictWriter(outfile, delimiter=';', lineterminator='\n', fieldnames=fieldnames)writer.writeheader()## Añadir para cada usuario el nombre completo y correo electrónico y para cada grupo un 1 o 0, dependiendo de la membresía del grupo<\/span>for user in my_users: membership = []try: thisUser = {} thisUser['USERNAME'] = user.fullName thisUser['EMAIL'] = user.emailtry: # La pertenencia a grupos fuera de la organización generará un error ("No tienes permisos para acceder a este recurso o realizar esta operación.")for group in user.groups: membership.append(group.title)except:passfor title in my_group_titles:if title in membership: thisUser[title] = 1else: thisUser[title] = 0except:print("NOTA: no se puede recuperar información sobre el usuario "+user.fullName+".")pass writer.writerow(thisUser)outfile.close()print ("Listo: "+datetime.datetime.today().strftime('%c'))print()print()</ span >print </ span >< spanclass= " punctuationtoken ">( </ span >< spanclass= " stringtoken ">'El archivo CSV se puede encontrar aquí:' </ span >< spanclass= " punctuationtoken ">) </ span >print </ span >< spanclass= " punctuationtoken ">( </ span >os. </ span >path. </ span >abspath( </ span >fname) </ span >< spanclass= " punctuationtoken ">) </ span >print </ span >< spanclass= " punctuationtoken ">( </ span >< spanclass= " stringtoken ">'===================' </ span >< spanclass= " punctuationtoken ">) </ span >< spanclass= " line-numbers-rows ">< span >< < EMOJI_0 > ></ span >< span >< < EMOJI_1 > ></ span >< span >< < EMOJI_2 > ></ span >< span >< < EMOJI_3 > ></ span >< span >< < EMOJI_4 > ></ span >< span >< < EMOJI_5 > ></ span >< span >< < EMOJI_6 > ></ span >< span >< < EMOJI_7 > ></ span >< span >< < EMOJI_8 > ></ span >< span >< < EMOJI_9 > ></ span >< span >< < EMOJI_10 > ></ span >< span >< < EMOJI_11 > ></ span >< span >< < EMOJI_12 > ></ span >< span >< < EMOJI_13 > ></ span >< span >< < EMOJI_14 > ></ span >< span >< < EMOJI_15 > ></ span >< span >< < EMOJI_16 > ></ span >< span >< < EMOJI_17 > ></ span >< span >< < EMOJI_18 > ></ span >< span >< < EMOJI_19 > ></ span >< span >< < EMOJI_20 > ></ span >< span >< < EMOJI_21 > ></ span >< span >< < EMOJI_22 > ></ span >< span >< < EMOJI_23 > ></ span >< span >< < EMOJI_24 > ></ span >< span >< < EMOJI_25 > ></ span >< span >< < EMOJI_26 > ></ span >< span >< < EMOJI_27 > ></ span >< span >< < EMOJI_28 > ></ span >< ... (continúa con los emojis sin traducir) ...Y aquí está el script de provide_credentials que se usa arriba para iniciar sesión en AGOL:import json, osfrom getpass import getpass # para aceptar contraseñas de forma interactivadef provide_credentials(): file_with_credentials = 'my_credentials.json' username = '' password = '' if os.path.exists(file_with_credentials): with open(file_with_credentials) as f: data = json.load(f) username = data['username'] password = data['password'] if not username or username == 'USERNAME' or not password or password == 'PASSWORD': username = input('Por favor ingrese su nombre de usuario: ') password = getpass('Por favor ingrese su contraseña (esto permanecerá invisible): ') return username, passwordCon el archivo de entrada my_credentials.json:{ "username":"USERNAME", "password":"PASSWORD"}¡Feliz codificación!Egge-Jan
## ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++<\/SPAN>## Información de Gestión de ArcGIS Online<\/SPAN>## Script: agol_group_membership.py<\/SPAN>## Objetivo: crear una visión general de la membresía de grupos en tu organización ArcGIS Online<\/SPAN>## Autor: Egge-Jan Polle - Tensing GIS Consultancy<\/SPAN>## Fecha: 3 de agosto de 2018<\/SPAN>## ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++<\/SPAN>#<\/SPAN># Este script debe ejecutarse dentro de un entorno específico ArcGIS/Python usando el archivo batch abajo<\/SPAN># (Este archivo batch viene con la instalación de ArcGIS Pro)<\/SPAN># "C:\Program Files\ArcGIS\Pro\bin\Python\scripts\propy.bat" agol_group_membership.py<\/SPAN>#<\/SPAN>import<\/SPAN> csv, <\/span>os, <\/span> sysfrom arcgis.gis import GISfrom provide_credentials import provide_credentialsprint('===================')print('El script que se está ejecutando: ' + __file__)print('Primero debes iniciar sesión en ArcGIS Online')# Iniciar sesión<\/span>username, password = provide_credentials()my_agol = GIS("https://www.arcgis.com", username, password)print("Inicio: " + datetime.datetime.today().strftime('%c'))## Obtener todos los grupos<\/span>my_groups = my_agol.groups.search()## Opcionalmente: echar un vistazo a todos los grupos<\/span>#my_groups## Opcionalmente: contar el número de grupos<\/span>#len(my_groups)## Obtener todos los usuarios<\/span>my_users = my_agol.users.search(max_users = 350) # El valor predeterminado max_users = 100, así que aumentalo si tienes más## Opcionalmente: echar un vistazo a todos los usuarios<\/span>#my_users## Opcionalmente: contar el número de usuarios<\/span>#len(my_users)## Crear una lista con todos los títulos de grupo<\/span>my_group_titles = []for my_group in my_groups: my_group_titles.append(my_group.title)## Crear una lista con nombres de campos<\/span>fieldnames = []fieldnames = ['USERNAME','EMAIL']for title in my_group_titles: fieldnames.append(title)## Opcionalmente: echar un vistazo a los nombres de campos<\/span>#fieldnames## Crear un archivo CSV con una matriz de los grupos con sus miembros<\/span>today = datetime.datetime.today().strftime('%Y%m%d')fname = 'AGOL_Group_Membership' + today + '.csv'try: os.remove(fname)except OSError:passoutfile = open(fname, 'a')writer = csv.DictWriter(outfile, delimiter=';', lineterminator='\n', fieldnames=fieldnames)writer.writeheader()## Añadir para cada usuario el nombre completo y correo electrónico y para cada grupo un 1 o 0, dependiendo de la membresía del grupo<\/span>for user in my_users: membership = []try: thisUser = {} thisUser['USERNAME'] = user.fullName thisUser['EMAIL'] = user.emailtry: # La pertenencia a grupos fuera de la organización generará un error ("No tienes permisos para acceder a este recurso o realizar esta operación.")for group in user.groups: membership.append(group.title)except:passfor title in my_group_titles:if title in membership: thisUser[title] = 1else: thisUser[title] = 0except:print("NOTA: no se puede recuperar información sobre el usuario "+user.fullName+".")pass writer.writerow(thisUser)outfile.close()print ("Listo: "+datetime.datetime.today().strftime('%c'))print()print()</ span >print </ span >< spanclass= " punctuationtoken ">( </ span >< spanclass= " stringtoken ">'El archivo CSV se puede encontrar aquí:' </ span >< spanclass= " punctuationtoken ">) </ span >print </ span >< spanclass= " punctuationtoken ">( </ span >os. </ span >path. </ span >abspath( </ span >fname) </ span >< spanclass= " punctuationtoken ">) </ span >print </ span >< spanclass= " punctuationtoken ">( </ span >< spanclass= " stringtoken ">'===================' </ span >< spanclass= " punctuationtoken ">) </ span >< spanclass= " line-numbers-rows ">< span >< < EMOJI_0 > ></ span >< span >< < EMOJI_1 > ></ span >< span >< < EMOJI_2 > ></ span >< span >< < EMOJI_3 > ></ span >< span >< < EMOJI_4 > ></ span >< span >< < EMOJI_5 > ></ span >< span >< < EMOJI_6 > ></ span >< span >< < EMOJI_7 > ></ span >< span >< < EMOJI_8 > ></ span >< span >< < EMOJI_9 > ></ span >< span >< < EMOJI_10 > ></ span >< span >< < EMOJI_11 > ></ span >< span >< < EMOJI_12 > ></ span >< span >< < EMOJI_13 > ></ span >< span >< < EMOJI_14 > ></ span >< span >< < EMOJI_15 > ></ span >< span >< < EMOJI_16 > ></ span >< span >< < EMOJI_17 > ></ span >< span >< < EMOJI_18 > ></ span >< span >< < EMOJI_19 > ></ span >< span >< < EMOJI_20 > ></ span >< span >< < EMOJI_21 > ></ span >< span >< < EMOJI_22 > ></ span >< span >< < EMOJI_23 > ></ span >< span >< < EMOJI_24 > ></ span >< span >< < EMOJI_25 > ></ span >< span >< < EMOJI_26 > ></ span >< span >< < EMOJI_27 > ></ span >< span >< < EMOJI_28 > ></ span >< ... (continúa con los emojis sin traducir) ...Y aquí está el script de provide_credentials que se usa arriba para iniciar sesión en AGOL:import json, osfrom getpass import getpass # para aceptar contraseñas de forma interactivadef provide_credentials(): file_with_credentials = 'my_credentials.json' username = '' password = '' if os.path.exists(file_with_credentials): with open(file_with_credentials) as f: data = json.load(f) username = data['username'] password = data['password'] if not username or username == 'USERNAME' or not password or password == 'PASSWORD': username = input('Por favor ingrese su nombre de usuario: ') password = getpass('Por favor ingrese su contraseña (esto permanecerá invisible): ') return username, passwordCon el archivo de entrada my_credentials.json:{ "username":"USERNAME", "password":"PASSWORD"}¡Feliz codificación!Egge-Jan
Forgive my ignorance but where in the world would
<SPAN class="" style="color: #0077aa; border: 0px; font-weight: inherit;">print</SPAN><SPAN class="" style="color: #999999; border: 0px; font-weight: inherit;">(</SPAN>os<SPAN class="" style="color: #999999; border: 0px; font-weight: inherit;">.</SPAN>path<SPAN class="" style="color: #999999; border: 0px; font-weight: inherit;">.</SPAN>abspath<SPAN class="" style="color: #999999; border: 0px; font-weight: inherit;">(</SPAN>fname<SPAN class="" style="color: #999999; border: 0px; font-weight: inherit;">)</SPAN><SPAN class="" style="color: #999999; border: 0px; font-weight: inherit;">)</SPAN>
be if I ran this on and Enterprise Notebook?
I ran this with no errors and it said:
=================== The CSV file can be found here: /arcgis/AGOL_Group_Membership20200416.csv =================== But I cannot find this file
Hi Jeff Timm,
Has the file not just been created in the same folder where the Python script resides?
BR,
Egge-Jan
Egge-Jan Pollé, this seems extremely useful, and I really appreciate you sharing! This is the type of more advanced GIS work (utilizing the API's) that I want to get in to, but for someone who is a complete newbie, I'm a bit unclear where to start. I've written/modified scripts to use in geoprocessing, but never involving multiple python files or interacting with my Organization account. Do you think you could go into a bit more detail how to approach this? (also, does this script work with both AGOL and Enterprise accounts?)
I created the JSON file and two separate .PY scripts from the code you provided, all in the same folder. Then I added the "agol_group_membership.py" script to a toolbox in ArcGIS Pro and attempted to run the tool. This is the error message I got:
Obviously I'm just not understanding how to set it up correctly. I know it's a lot to ask, but if you could at least maybe share a resource that helps explain how to get started with this stuff that would be SO helpful!
Wishing you all the best,
Katherine
Hi Katherine Clark,
Please have a look at the screen capture of the DOSBox below.
Please note: It is very important to run this script in combination with the bat file mentioned to make sure you run it in the correct ArcGIS/Python environment (This batch file comes with the installation of ArcGIS Pro). Without making sure you use this correct environment the script will fail anyway...
Please let me know if this works for you.
Stay safe, stay home - have a nice weekend.
Thank you! I got it to run once I changed the credentials in the JSON to be my ArcGIS Online login rather than my Enterprise login (is there a way to make this work with Enterprise?)
Strangely, I did receive these messages about not having permissions:
However, there was a csv produced in the same folder where the scripts are stored, as expected. The only bad part....the csv has different rows for each user, but no column separations. Have you experienced this before?
Update: I was able to correct the csv file by using the "Text to Columns" tool in the Data tab of the Excel Ribbon since all the values were neatly separated by semi colons.
However, still curious if this is expected behavior for the output of the script.
Dumb question. I wanted to find documentation about this:
"gis.users.search(max_count=...)"
Where would I find it? The answer will be embarrassing, but I can't find it. I've searched the ArcGIS API for python documentation and I don't see an explanation of this property.
I was getting a list of users and did not realize there was a limit of 100 returned and was getting extremely frustrated with the results, wondering why they were incomplete. I found your post and discovered the "max_count" property, and am now wondering how I could go straight to the source and find such information more directly.
Thank you,
Randy McGregor
Easiest way to get it to get it to automatically open in Excel as a table is to change the delimiter to a comma from a semi colon. Since we can use whatever delimeters we wish the decision on what to include here is based on the needs of the client application that will be consuming the output.
Not sure if anyone answered your question regarding making it work with Enterprise.
The answer is yes it will work with any 'portal' of whether that portal is enterprise on premesis, cloud, or arcgisonline.
Just enter the details of the portal under the login comment at the top.
<SPAN class="" style="color: slategray; border: 0px; font-weight: inherit;"># Log in</SPAN> username<SPAN class="" style="color: #999999; border: 0px; font-weight: inherit;">,</SPAN> password <SPAN class="" style="color: #a67f59; background: rgba(255, 255, 255, 0.5); border: 0px; font-weight: inherit;">=</SPAN> provide_credentials<SPAN class="" style="color: #999999; border: 0px; font-weight: inherit;">(</SPAN><SPAN class="" style="color: #999999; border: 0px; font-weight: inherit;">)</SPAN> my_agol <SPAN class="" style="color: #a67f59; background: rgba(255, 255, 255, 0.5); border: 0px; font-weight: inherit;">=</SPAN> GIS<SPAN class="" style="color: #999999; border: 0px; font-weight: inherit;">(</SPAN><SPAN class="" style="color: #669900; border: 0px; font-weight: inherit;"><SPAN style="border: 0px; font-weight: inherit;"><SPAN>"</SPAN><A _jive_internal="true" href="https://community.esri.com/yourEnterprise.com/PortalWebadaptor" target="_blank">https://yourEnterprise.com/PortalWebadaptor</A></SPAN><SPAN style="border: 0px; font-weight: inherit;">"</SPAN></SPAN><SPAN class="" style="color: #999999; border: 0px; font-weight: inherit;">,</SPAN> username<SPAN class="" style="color: #999999; border: 0px; font-weight: inherit;">,</SPAN> password<SPAN class="" style="color: #999999; border: 0px; font-weight: inherit;">)</SPAN>
If the variable name "my_agol" seems a bit like a mental roadblock, you can rename it throughout the script to something like "my_portal".
Egge-Jan shared a highly adaptable and fantastically useful nugget of code here that makes short work of pulling info into spreadsheets about users and groups.
If like me you want the code to work on all your portals without much modification there are a few things you can do such as automatically naming your output csv by pulling the portal name directly via implementation of "my_portal.properties.portalName" in the fname= variable.
Could anyone suggest how this could be modified to list users within the Groups, where those users are not from the same organisation? I can get it to list our organisation's users and their Group memberships, but it excludes the hundreds of users we have in those Groups within our hub community organisation.Many thanks.
Los miembros registrados pueden publicar, seguir actualizaciones y más. ¿Nuevo aquí? Regístrate gratis.
Find useful guides, FAQs, and documents to help you navigate and make the most of Esri Community.