elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado:


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  C# Identificar usuario WindowsIdentity
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: C# Identificar usuario WindowsIdentity  (Leído 3,510 veces)
Andrew06

Desconectado Desconectado

Mensajes: 4



Ver Perfil
C# Identificar usuario WindowsIdentity
« en: 24 Septiembre 2014, 07:02 am »

Hola

Estoy realizando un monitor de eventos en un directorio cuando un archivo es cambiado me realiza una alerta

lo que necesito es identificar que usuario esta realizando el cambio estoy utilizando el siguiente código pero solo me trae el usuario local

Código:
WindowsIdentity id = WindowsIdentity.GetCurrent();
 string login = id.Name;
 Console.WriteLine(login);

Por favor su ayuda con este tema soy un poco nuevo en C Sharp consola de windows


En línea

Eleкtro
Ex-Staff
*
Conectado Conectado

Mensajes: 9.813



Ver Perfil
Re: C# Identificar usuario WindowsIdentity
« Respuesta #1 en: 24 Septiembre 2014, 11:23 am »

Con la Class WindowsIdentity no vas a conseguir nada, el método GetCurrent devuelve el usuario local, y debes conocer el nombre del usuario (o el UPN si no formas parte de un dominio) para identificar un usuario usando el Constructor de dicha Class.

Aparte de eso, un FilesystemWatcher no recibe ni devuelve ningún tipo de información sobre el usuario en cuestión, según parece es una tarea bastante compleja de llevar a cabo, tienes mucha información sobre esto en los resultados de Google:

NTFS doesn't track who deletes, renames, or modifies a file, so there's no way you can get the username. It only keeps track of who OWNS the file.

No, it's not possible, the NTFS or FAT file system which is what Windows uses doesn't record this information. The best you could get about a file is last time it was changed.

First off, you'll need to devise some way of determining whether the changes to a file were made locally or remotely

The only possibilities I can think of would be the NetFileEnum and NetFileGetInfo API function calls

This isn't currently possible with the current implementations of the FileSystemWatcher as it does not receive this type of information when a file is deleted, or anything about a file changes.
You would need to use Win32 API calls, if it's possible at all. I'm not sure which APIs you would need to use,
but you will end up essentially writing your own version of a file system watcher

I was looking for the same thing today. I found something that will work.
See here: http://stackoverflow.com/questions/7861512/get-username-of-an-accesed-file

Keep in mind, auditing must be enabled for the folder.



La información de la función NetFileGetInfo es muy escasa así que no puedo mostrarte un ejemplo funcional (tampoco se si funcionaría, solo especulan por internet).
( http://msdn.microsoft.com/en-us/library/windows/desktop/bb525379%28v=vs.85%29.aspx )

Puedes probar la siguiente solución (ya no recuerdo de donde obtuve el código) sacada de: http://stackoverflow.com/questions/11660235/find-out-usernamewho-modified-file-in-c-sharp, pero personalmente y al menos en Windows 8.1 a mi me devuelve el grupo de usuarios (Administradores), no el usuario (Administrador).

La versión en VB.NET
Código
  1. Imports System.Text
  2. Imports System.IO
  3.  
  4. Public Class Form1
  5.  
  6.    Private Function GetSpecificFileProperties(file As String, ParamArray indexes As Integer()) As String
  7.  
  8.        Dim fileName As String = Path.GetFileName(file)
  9.        Dim folderName As String = Path.GetDirectoryName(file)
  10.        Dim shell As New Shell32.Shell()
  11.        Dim objFolder As Shell32.Folder
  12.        objFolder = shell.[NameSpace](folderName)
  13.        Dim sb As New StringBuilder()
  14.        For Each item As Shell32.FolderItem2 In objFolder.Items()
  15.            If fileName = item.Name Then
  16.                For i As Integer = 0 To indexes.Length - 1
  17.                    sb.Append(objFolder.GetDetailsOf(item, indexes(i)) + ",")
  18.                Next
  19.                Exit For
  20.            End If
  21.        Next
  22.        Dim result As String = sb.ToString().Trim()
  23.        If result.Length = 0 Then
  24.            Return String.Empty
  25.        End If
  26.        Return result.Substring(0, result.Length - 1)
  27.  
  28.    End Function
  29.  
  30.    Private Sub FileSystemWatcher1_Changed(sender As Object, e As FileSystemEventArgs) _
  31.    Handles FileSystemWatcher1.Changed, FileSystemWatcher1.Created
  32.  
  33.        Dim filepath As String = e.FullPath
  34.  
  35.        Dim Type As String = GetSpecificFileProperties(filepath, 2)
  36.        Dim ObjectKind As String = GetSpecificFileProperties(filepath, 11)
  37.        Dim CreatedDate As DateTime = Convert.ToDateTime(GetSpecificFileProperties(filepath, 4))
  38.        Dim LastModifiedDate As DateTime = Convert.ToDateTime(GetSpecificFileProperties(filepath, 3))
  39.        Dim LastAccessDate As DateTime = Convert.ToDateTime(GetSpecificFileProperties(filepath, 5))
  40.        Dim LastUser As String = GetSpecificFileProperties(filepath, 10)
  41.        Dim ComputerName As String = GetSpecificFileProperties(filepath, 53)
  42.        Dim FileSize As String = GetSpecificFileProperties(filepath, 1)
  43.  
  44.        Debug.WriteLine(LastUser)
  45.        Debug.WriteLine(ComputerName)
  46.  
  47.    End Sub
  48.  
  49. End Class



Esta parece ser una solución, aunque personalmente no la he consguido hacer funcionar:
http://vbcity.com/forums/p/133307/698930.aspx#698930
+
Use code posted by dave4dl and update declare struct FILE_INFO_3 as following, you can monitor user name of create and update file action(It is like to combination of FileSystemWatcher and OpenFiles.exe's functions of FileSharing Server)
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct FILE_INFO_3
{
    public int fi3_id;
    public int fi3_permission;
    public int fi3_num_locks;
    [MarshalAs(UnmanagedType.LPWStr)]
    public string fi3_pathname;
    [MarshalAs(UnmanagedType.LPWStr)]
    public string fi3_username;
}

Saludos.


« Última modificación: 24 Septiembre 2014, 11:29 am por Eleкtro » En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
identificar al usuario
Programación Visual Basic
alfredo08 2 1,694 Último mensaje 10 Septiembre 2008, 14:03 pm
por alfredo08
¿Identificar a un usuario a través de su avatar?
Noticias
wolfbcn 4 3,331 Último mensaje 7 Agosto 2011, 17:02 pm
por EFEX
Como identificar un usuario de un foro?
Hacking
perdio 5 4,674 Último mensaje 8 Agosto 2012, 11:36 am
por perdio
como saber la pass del usuario administrador siendo usuario estandar.
Windows
er.ring 0 3,030 Último mensaje 3 Mayo 2014, 18:12 pm
por er.ring
Identificar Usuario Normal Y Usuario Administrador
PHP
Xx Zode xX 7 4,332 Último mensaje 1 Diciembre 2016, 06:47 am
por engel lex
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines