Título: [VBS] Saber si eres administrador
Publicado por: MeCraniDOS en 23 Febrero 2014, 19:41 pm
Hola a todos,
Estoy intentando saber si eres administrador desde vbs, he publicado este post en Visual Basic, con unos trozos de código, pero quizas con vbs es más fácil, a ver si me pueden dar ideas... :huh: :huh:
Visual Basic: http://foro.elhacker.net/programacion_visual_basic/saber_si_eres_administrador_vb6-t409096.0.html (http://foro.elhacker.net/programacion_visual_basic/saber_si_eres_administrador_vb6-t409096.0.html)
Saludos
Título: Re: [VBS] Saber si eres administrador
Publicado por: Eleкtro en 24 Febrero 2014, 00:09 am
No le encuentro sentido a que quieras investigar la manera de llevar a cabo esta tarea en un lenguaje inferior al que estabas usando. EDITO: Acabo de darme cuenta que, en el otro post, dices que la API no te da los resultados esperados en windows 8, bueno, esto la verdad es que en VBNET sería mucho más simple que usando API's, en 4 líneas de código, pero usando VB6 podrías probar a utilizar el método NetUserGetInfo (http://msdn.microsoft.com/en-us/library/windows/desktop/aa370654%28v=vs.85%29.aspx) de la WinAPI donde en el miembro usri2_priv de la estructura USER_INFO_2 (http://msdn.microsoft.com/en-us/library/windows/desktop/aa371337%28v=vs.85%29.aspx) se supone que podrías verificar si es admin o no. Aquí tienes unas pistas de como usarlo: http://www.vbforums.com/showthread.php?280359-check-if-user-is-admin
De todas formas, sabiendo que el inicio de la SID del grupo de Administradores (como los demás grupos de privilegios Elevados, etc) es un identificador constante, creo que sería suficiente con listar los grupos a los que pertenece el usuario actual y buscar el SID correspondiente al grupo. Así pues, este es mi enfoque de como hacerlo de una manera sencilla en VBS (como querías): ' Check if User is an Administrator ' ( By Elektro ) Const AdminSID= "S-1-5-32-544" UserName = CreateObject("WScript.Network").UserName IsAdmin = Not CBool(CreateObject("WScript.Shell"). _ Run("%ComSpec% /C WhoAmI.exe /All | Find """ & AdminSID & """", 0, True)) MsgBox "'" & UserName & "'" & _ " " & "Is Administrator?: " & IsAdmin, _ 64, "Administrator check" Wscript.Quit(CInt(Not IsAdmin)) ' 0 = Success (IsAdmin), -1 = Failed (IsNotAdmin)
Saludos!
Título: Re: [VBS] Saber si eres administrador
Publicado por: MeCraniDOS en 24 Febrero 2014, 22:16 pm
En Windows 8 siempre devuelve Falso.. :rolleyes:
Muchas gracias por la info y por el ejemplo en vbs, investigaré el método y te digo que tal ;D
Saludos
Título: Re: [VBS] Saber si eres administrador
Publicado por: Eleкtro en 25 Febrero 2014, 06:39 am
Si devuelve Falso es porque no eres Admin, quizás sólamente eres usuario con privilegios elevados, pero no Administrador.
PD: Yo uso Windows 8.
Saludos
Título: Re: [VBS] Saber si eres administrador
Publicado por: fary en 25 Febrero 2014, 09:56 am
La función IsUserAnAdmin solo funciona desde XP a vista. Te recomiendo que uses CheckTokenMembership, que funciona desde XP hasta 8. http://msdn.microsoft.com/en-us/library/windows/desktop/aa376389%28v=vs.85%29.aspx Ejemplo de la msdn en C++ BOOL IsUserAdmin(VOID) /*++ Routine Description: This routine returns TRUE if the caller's process is a member of the Administrators local group. Caller is NOT expected to be impersonating anyone and is expected to be able to open its own process and process token. Arguments: None. Return Value: TRUE - Caller has Administrators local group. FALSE - Caller does not have Administrators local group. -- */ { BOOL b; SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY; PSID AdministratorsGroup; b = AllocateAndInitializeSid( &NtAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &AdministratorsGroup); if(b) { if (!CheckTokenMembership( NULL, AdministratorsGroup, &b)) { b = FALSE; } FreeSid(AdministratorsGroup); } return(b); }
Un saludo.
Título: Re: [VBS] Saber si eres administrador
Publicado por: MeCraniDOS en 26 Febrero 2014, 23:15 pm
Si devuelve Falso es porque no eres Admin, quizás sólamente eres usuario con privilegios elevados, pero no Administrador.
PD: Yo uso Windows 8.
Saludos
Estoy probando tu script, y ejecutandolo en Windows XP, desde la cuenta de administrador me devuelve Falso... :-\La función IsUserAnAdmin solo funciona desde XP a vista. Te recomiendo que uses CheckTokenMembership, que funciona desde XP hasta 8.
He encontrado esta función, pero veo mucho código y no se muy bien que es lo que hace la función en sí (Utiliza la función que me has dicho) :rolleyes:Option Explicit Private Const TOKEN_DUPLICATE = &H2& Private Const TOKEN_QUERY = &H8& Private Const ERROR_NO_TOKEN = 1008 Private Const SECURITY_BUILTIN_DOMAIN_RID = &H20& Private Const DOMAIN_ALIAS_RID_ADMINS = &H220& Private Const SECURITY_NT_AUTHORITY = &H5& Private Type SID_IDENTIFIER_AUTHORITY Value(6) As Byte End Type Private Enum SECURITY_IMPERSONATION_LEVEL SecurityAnonymous SecurityIdentification SecurityImpersonation SecurityDelegation End Enum Private Declare Function OpenProcessToken Lib "advapi32" (ByVal ProcessHandle As Long, ByVal DesiredAccess As Long, ByRef TokenHandle As Long) As Long Private Declare Function OpenThreadToken Lib "advapi32" (ByVal ThreadHandle As Long, ByVal DesiredAccess As Long, ByVal OpenAsSelf As Long, ByRef TokenHandle As Long) As Long Private Declare Function AllocateAndInitializeSid Lib "advapi32" (ByRef pIdentifierAuthority As SID_IDENTIFIER_AUTHORITY, ByVal nSubAuthorityCount As Byte, ByVal nSubAuthority0 As Long, ByVal nSubAuthority1 As Long, ByVal nSubAuthority2 As Long, ByVal nSubAuthority3 As Long, ByVal nSubAuthority4 As Long, ByVal nSubAuthority5 As Long, ByVal nSubAuthority6 As Long, ByVal nSubAuthority7 As Long, ByRef lpPSid As Long) As Long Private Declare Function CheckTokenMembership Lib "advapi32" (ByVal TokenHandle As Long, ByVal SidToCheck As Long, ByRef IsMember As Long) As Long Private Declare Function DuplicateToken Lib "advapi32" (ByVal ExistingTokenHandle As Long, ByVal ImpersonationLevel As Long, ByRef DuplicateTokenHandle As Long) As Long Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long Private Declare Function GetCurrentProcess Lib "kernel32" () As Long Private Declare Function GetCurrentThread Lib "kernel32" () As Long Private Declare Sub FreeSid Lib "advapi32.dll" (ByVal pSid As Long) Public Function IsInRoleAdmin() As Boolean Dim NtAuthority As SID_IDENTIFIER_AUTHORITY Dim AdminGroup As Long Dim Success As Long Dim hToken As Long Dim hTokenDup As Long If OpenThreadToken(GetCurrentThread, TOKEN_DUPLICATE Or TOKEN_QUERY, True, hToken) = 0 Then OpenProcessToken GetCurrentProcess, TOKEN_DUPLICATE Or TOKEN_QUERY, hToken End If If DuplicateToken(hToken, SecurityImpersonation, hTokenDup) Then ' Well-known SIDs NtAuthority.Value(5) = SECURITY_NT_AUTHORITY ' allocates and initializes a security identifier (SID) Success = AllocateAndInitializeSid(NtAuthority, 2, _ SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, AdminGroup) If Success Then If CheckTokenMembership(hTokenDup, AdminGroup, Success) = 0 Then Success = 0 End If FreeSid AdminGroup End If End If IsInRoleAdmin = Success CloseHandle hToken CloseHandle hTokenDup End Function
Es decir, por ejemplo este trozo:Private Declare Function OpenProcessToken Lib "advapi32" (ByVal ProcessHandle As Long, ByVal DesiredAccess As Long, ByRef TokenHandle As Long) As Long Private Declare Function OpenThreadToken Lib "advapi32" (ByVal ThreadHandle As Long, ByVal DesiredAccess As Long, ByVal OpenAsSelf As Long, ByRef TokenHandle As Long) As Long Private Declare Function AllocateAndInitializeSid Lib "advapi32" (ByRef pIdentifierAuthority As SID_IDENTIFIER_AUTHORITY, ByVal nSubAuthorityCount As Byte, ByVal nSubAuthority0 As Long, ByVal nSubAuthority1 As Long, ByVal nSubAuthority2 As Long, ByVal nSubAuthority3 As Long, ByVal nSubAuthority4 As Long, ByVal nSubAuthority5 As Long, ByVal nSubAuthority6 As Long, ByVal nSubAuthority7 As Long, ByRef lpPSid As Long) As Long Private Declare Function CheckTokenMembership Lib "advapi32" (ByVal TokenHandle As Long, ByVal SidToCheck As Long, ByRef IsMember As Long) As Long Private Declare Function DuplicateToken Lib "advapi32" (ByVal ExistingTokenHandle As Long, ByVal ImpersonationLevel As Long, ByRef DuplicateTokenHandle As Long) As Long Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long Private Declare Function GetCurrentProcess Lib "kernel32" () As Long Private Declare Function GetCurrentThread Lib "kernel32" () As Long
Para que necesita esas declaraciones? OpenProccess, OpenThread... :huh:
Saludos
Título: Re: [VBS] Saber si eres administrador
Publicado por: fary en 28 Febrero 2014, 21:13 pm
Esas son las declaraciones de las funciones que se usan... Lee un poco mas sobre VB6.
Título: Re: [VBS] Saber si eres administrador
Publicado por: MeCraniDOS en 1 Marzo 2014, 10:12 am
Esas son las declaraciones de las funciones que se usan... Lee un poco mas sobre VB6.
Hasta ahí llego :¬¬ A lo que voy es que para que se necesita abrir un proceso, un thread, etc, sólo para saber sí eres administrador.. :huh:
Título: Re: [VBS] Saber si eres administrador
Publicado por: fary en 1 Marzo 2014, 11:57 am
Lo que hace es Obtener/Duplicar los derechos de inicio de sesión del usuario, pero esto no es necesario de hacer ya que en el ejemplo de la msdn no lo usan, ni indican que haya que hacerlo. Aquí te dejo el código en VB6 retocado. Option Explicit Private Const TOKEN_DUPLICATE = &H2& Private Const TOKEN_QUERY = &H8& Private Const ERROR_NO_TOKEN = 1008 Private Const SECURITY_BUILTIN_DOMAIN_RID = &H20& Private Const DOMAIN_ALIAS_RID_ADMINS = &H220& Private Const SECURITY_NT_AUTHORITY = &H5& Private Type SID_IDENTIFIER_AUTHORITY Value(6) As Byte End Type Private Enum SECURITY_IMPERSONATION_LEVEL SecurityAnonymous SecurityIdentification SecurityImpersonation SecurityDelegation End Enum Private Declare Function AllocateAndInitializeSid Lib "advapi32" (ByRef pIdentifierAuthority As SID_IDENTIFIER_AUTHORITY, ByVal nSubAuthorityCount As Byte, ByVal nSubAuthority0 As Long, ByVal nSubAuthority1 As Long, ByVal nSubAuthority2 As Long, ByVal nSubAuthority3 As Long, ByVal nSubAuthority4 As Long, ByVal nSubAuthority5 As Long, ByVal nSubAuthority6 As Long, ByVal nSubAuthority7 As Long, ByRef lpPSid As Long) As Long Private Declare Function CheckTokenMembership Lib "advapi32" (ByVal TokenHandle As Long, ByVal SidToCheck As Long, ByRef IsMember As Long) As Long Private Declare Sub FreeSid Lib "advapi32.dll" (ByVal pSid As Long) Private Sub form_load() If IsInRoleAdmin Then MsgBox "admin" Else MsgBox "NO" End If End Sub Public Function IsInRoleAdmin() As Boolean Dim NtAuthority As SID_IDENTIFIER_AUTHORITY Dim AdminGroup As Long Dim Success As Long ' Well-known SIDs NtAuthority.Value(5) = SECURITY_NT_AUTHORITY ' allocates and initializes a security identifier (SID) Success = AllocateAndInitializeSid(NtAuthority, 2, _ SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, AdminGroup) If CheckTokenMembership(0, AdminGroup, Success) = 0 Then Success = 0 End If FreeSid AdminGroup IsInRoleAdmin = Success End Function
Título: Re: [VBS] Saber si eres administrador
Publicado por: MeCraniDOS en 5 Marzo 2014, 21:44 pm
La función IsUserAnAdmin solo funciona desde XP a vista. Te recomiendo que uses CheckTokenMembership, que funciona desde XP hasta 8.
Gracias por la solucion en VB, pero al final he decidido hacerlo en C++, y probando la funcion que me has dicho, me da el siguiente error:error: 'CheckTokenMembership' was not declared in this scope Header: Winbase.h (include Windows.h) Como lo puedo solucionar? El código esta copiado de http://msdn.microsoft.com/en-us/library/windows/desktop/aa376389%28v=vs.85%29.aspx (http://msdn.microsoft.com/en-us/library/windows/desktop/aa376389%28v=vs.85%29.aspx) y no va... :rolleyes:
Saludos
Título: Re: [VBS] Saber si eres administrador
Publicado por: Eleкtro en 5 Marzo 2014, 22:45 pm
Gracias por la solucion en VB, pero al final he decidido hacerlo en C++ Si para ti no supone un problema realizar la comprobación de si el usuaro actual es Administrador en el lenguaje que sea, entonces yo te recomiendo VB.NET/CSharp, no necesitas manejar la WinAPI como estás intentando en VB6 y C++ (que también podrías hacerlo de esa manera), en .NET se puede lograr con un código reálmente simple y efectivo: ' Current User Is Admin? ' ( By Elektro ) ' ''' <summary> ''' Indicates whether the current logged user is an Administrator. ''' </summary> ''' <returns><c>true</c> if the current logged user is an Administrator, <c>false</c> otherwise.</returns> Public Function CurrentUserIsAdmin() As Boolean Dim Identity As Security.Principal.WindowsIdentity = Security.Principal.WindowsIdentity.GetCurrent Return New Security.Principal.WindowsPrincipal(Identity). IsInRole(Security.Principal.WindowsBuiltInRole.Administrator) End Function
Saludos
|