Find out who is running the process on the remote machine - vb.net

I am trying to get a list of processes running on remote machine and the username running them. So far I've got:
Dim ps As System.Diagnostics.Process
For Each ps In System.Diagnostics.Process.GetProcesses("myserver")
ListBox1.Items.Add(ps.ProcessName)
Next

How to get permissions for using System.Diagnostics.Process.GetProcess(string)? - this might be a better way to do it. It is in C# I can translate it if you want.
''' using System.Management;
' don't forget! in VS you may have to add a new reference to this DLL
Dim op As New ConnectionOptions()
op.Username = "REMOTE_USER"
op.Password = "REMOTE_PASSWORD"
Dim sc As New ManagementScope("\\REMOTE_COMPUTER_NAME\root\cimv2", op)
Dim query As New ObjectQuery("Select * from Win32_Process")
Dim searcher As New ManagementObjectSearcher(sc, query)
Dim result As ManagementObjectCollection = searcher.[Get]()
For Each obj As ManagementObject In result
If obj("Caption") IsNot Nothing Then
Console.Write(obj("Caption").ToString() & vbTab)
End If
If obj("CommandLine") IsNot Nothing Then
Console.WriteLine(obj("CommandLine").ToString())
End If
Next
Public Function GetProcessOwner(processId As Integer) As String
Dim query As String = "Select * From Win32_Process Where ProcessID = " & processId
Dim searcher As New ManagementObjectSearcher(query)
Dim processList As ManagementObjectCollection = searcher.[Get]()
For Each obj As ManagementObject In processList
Dim argList As String() = New String() {String.Empty, String.Empty}
Dim returnVal As Integer = Convert.ToInt32(obj.InvokeMethod("GetOwner", argList))
If returnVal = 0 Then
' return DOMAIN\user
Return argList(1) & "\" & argList(0)
End If
Next
Return "NO OWNER"
End Function

Related

ManagementException was Caught: Invalid class

I have the following Function intended to identify the username of the user who started a specific process:
Private Function GetProcessAssociatedUserID(ByVal processName As String) As String
Dim user(1) As String
Try
Dim query As New SelectQuery(processName)
Dim searcher As New System.Management.ManagementObjectSearcher(query)
For Each process As ManagementObject In searcher.Get()
process.InvokeMethod("GetOwner", CType(user, Object()))
Next
Catch ex As Exception
End Try
Return user(0)
End Function
However somewhere in the ForEach initiation i'm getting this "ManagementException was Caught: Invalid class" exception thrown into my catch block. I've been in through debug but still cant work out what is. Any help would be much appreciated.
You can try it accomplishing this way
Private Function GetProcessAssociatedUserID(ByVal processName As String) As String
Dim query = "Select * from Win32_Process Where Name = """ + processName + """"
Dim searcher = New ManagementObjectSearcher(query)
Dim processList = searcher.Get()
For Each mObj As ManagementObject In processList
Dim argList As String() = {String.Empty, String.Empty}
Dim returnVal = Convert.ToInt32(mObj.InvokeMethod("GetOwner", argList))
If returnVal = 0 Then
Return argList(1) + "\\" + argList(0)
End If
Next
Return ""
End Function
This snippet works with .NET Framework 3.5 and above. For more details you may refer using-managementobjectsearcher-in-systemmanagement-is-getting-compiling-errors

Mongodb Driver 2.0 find() in VB.net not working

I am trying to practice with the C# Driver 2.0 for MongoDB. I don't know C# so I am writing the code in Visual Basic.
When I try to print out a list code won't compile. I know I have the For Each contents commented out but that's not the problem. I want to query the db for all documents in a collection and print them out to a text box.
Below is the code that isn't working. The last part is giving me trouble.
Private Sub btnListUsers_Click(sender As Object, e As EventArgs) Handles btnListUsers.Click
Dim ConnString As String
ConnString = txtConnStr.Text
Dim vDbName As String
vDbName = txtDb.Text
Dim vColName As String
vColName = txtColl.Text
Dim vClient As MongoClient
vClient = DbConnection(ConnString, vDbName, vColName)
Dim vDb As MongoDatabaseBase
vDb = vClient.GetDatabase(vDbName)
Dim vCol As IMongoCollection(Of BsonDocument)
vCol = vDb.GetCollection(Of BsonDocument)(vColName)
Dim query As BsonDocument
query = New BsonDocument("Names", txtListUsers.Text)
For Each item As BsonDocument In vCol.Find(query).ToListAsync()
'print a count
'print bson document
Next
End Sub
Any help is appreciated. I have been banging my head against the keyboard for hours.
BELOW IS THE CODE THAT WORKED FOR ME AFTER ALEX GAVE ME AN ANSWER:
Private Async Sub btnListUsers_Click(sender As Object, e As EventArgs) Handles btnListUsers.Click
Dim ConnString As String
ConnString = txtConnStr.Text
Dim vDbName As String
vDbName = txtDb.Text
Dim vColName As String
vColName = txtColl.Text
Dim vClient As MongoClient
vClient = DbConnection(ConnString, vDbName, vColName)
Dim vDb As MongoDatabaseBase
vDb = vClient.GetDatabase(vDbName)
Dim vCol As IMongoCollection(Of BsonDocument)
vCol = vDb.GetCollection(Of BsonDocument)(vColName)
Dim query As BsonDocument
query = New BsonDocument("Name", txtListUsers.Text)
Dim myList As List(Of BsonDocument) = Await vCol.Find(query).ToListAsync()
Dim i As Integer = 0
For Each vItem As BsonDocument In myList
'count
i += 1
'print bson document
rtfDataDisplay.Text = rtfDataDisplay.Text & vbCrLf & "#" & i.ToString & " - " & vItem.ToString & vbCrLf
Next
End Sub
I had to add Async to the sub. I also had my key "Name" incorrect. After that things went smoothly. Woo Hoo!
Your problem is in this line:
For Each item As BsonDocument In vCol.Find(query).ToListAsync()
The call to the ToListAsync() method returns an awaitable Task(Of List(Of BsonDocument)), i.e. a promise that it will return a list that you can enumerate when it has completed fetching it. You need to Await it, to get to the list. As in:
Dim myList As List(Of BsonDocument) = Await vCol.Find(query).ToListAsync()
For Each item As BsonDocument in myList
'print a count
'print bson document
Next
An alternative construct offered by the MongoDB driver, is to use its ForEachAsync method, and supply it with a lambda delegate argument.

how I can get the process username

I wanna get process username a try p.StartInfo.UserName but it return Empty string
I run this code from windows service because I need to know how users logon the PC from service and write Event Log
Public Function GetUserName(ByVal ProcessName As String)
Dim selectQuery As SelectQuery = New SelectQuery("Win32_Process")
Dim searcher As ManagementObjectSearcher = New ManagementObjectSearcher(selectQuery)
Dim y As System.Management.ManagementObjectCollection
y = searcher.Get
For Each proc As ManagementObject In y
Dim s(1) As String
proc.InvokeMethod("GetOwner", CType(s, Object()))
Dim n As String = proc("Name").ToString()
If n = ProcessName & ".exe" Then
Return ("User: " & s(1) & "\\" & s(0))
End If
Next
End Function
Me.txtUser.Text = Environment.UserName
Me.txtDomain.Text = Environment.UserDomainName

Vb.net get username that is running process

I'm making a program that looks for processes and can see which user is using them. I've got the scanning code, but not the username code. The username has to be a string. For example: I have 2 people running some processes and the processes will show in the listview. The first column is for processes and the second is for the username. I want it to be like:
(process here) (username here)
(process here) (username here)....
You get the point I think and there's much more processes than that running on the computer. The question is: How do you get the username for someone using the process?
Edit: The code. This is my code.
For Each pr As Process In Process.GetProcesses
Dim lvi As ListViewItem = ListView1.Items.Add(CStr(pr.ProcessName))
'Now I need something to put for the username
Next
This is the other one that is most common.
Public Function GetProcessOwner(processId As Integer) As String
Dim query As String = "Select * From Win32_Process Where ProcessID = " + processId
Dim searcher As New ManagementObjectSearcher(query)
Dim processList As ManagementObjectCollection = searcher.[Get]()
For Each obj As ManagementObject In processList
Dim argList As String() = New String() {String.Empty, String.Empty}
Dim returnVal As Integer = Convert.ToInt32(obj.InvokeMethod("GetOwner", argList))
If returnVal = 0 Then
' argList(0) == User
' argList(1) == DOMAIN
Return argList(0)
End If
Next
Return "NO OWNER"
End Function
This code is taken from here, where you can find more information if you need it. Basically, on a console app this will print the process name and the user to the screen:
Public Shared Sub Main()
Dim selectQuery As SelectQuery = New SelectQuery("Win32_Process")
Dim searcher As ManagementObjectSearcher = New
ManagementObjectSearcher(selectQuery)
For Each proc As ManagementObject In searcher.Get
Console.WriteLine(proc("Name").ToString)
Dim s(1) As String
proc.InvokeMethod("GetOwner", CType(s, Object()))
Console.WriteLine(("User: " & (s(1) + ("\\" + s(0)))))
Next
Console.ReadLine()
End Sub
This could be implemented as a function, like:
Public Function GetUserName(ByVal ProcessName As String)
Dim selectQuery As SelectQuery = New SelectQuery("Win32_Process")
Dim searcher As ManagementObjectSearcher = New ManagementObjectSearcher(selectQuery)
Dim y As System.Management.ManagementObjectCollection
y = searcher.Get
For Each proc As ManagementObject In y
Dim s(1) As String
proc.InvokeMethod("GetOwner", CType(s, Object()))
Dim n As String = proc("Name").ToString()
If n = ProcessName & ".exe" Then
Return ("User: " & s(1) & "\\" & s(0))
End If
Next
End Function
Just for reference, proc.InvokeMethod("GetOwner", CType(s, Object())) will return an array like this:
Index 0: Owner/user name
Index 1: Domain
And in our case, will store it in s(1).
Hope this helps :)
Notes:
If the function returns something like User: \\ then the process is probably a special windows process. To see which processes will act like this (for windows users):
Right click on the task bar
Select Start Task Manager
In the Processes tab, in the User Name column, some processes will have a blank cell instead of a user name.
Edit:
The VB.NET function has been edited and should now work, although I have no idea why the console program still worked. At any rate I've left it alone, if it still works why change it?

Best way to query disk space on remote server

I am trying to nail down free space on a remote server by querying all the drives and then looping until I find the drive I am seeking.
Is there a better way to do this?
Dim oConn As New ConnectionOptions
Dim sNameSpace As String = "\\mnb-content2\root\cimv2"
Dim oMS As New ManagementScope(sNameSpace, oConn)
Dim oQuery As System.Management.ObjectQuery = New System.Management.ObjectQuery("select FreeSpace,Size,Name from Win32_LogicalDisk where DriveType=3")
Dim oSearcher As ManagementObjectSearcher = New ManagementObjectSearcher(oMS, oQuery)
Dim oReturnCollection As ManagementObjectCollection = oSearcher.Get()
Dim oReturn As ManagementObject
For Each oReturn In oReturnCollection
'Disk name
Console.WriteLine("Name : " + oReturn("Name").ToString())
'Free Space in bytes
Dim sFreespace As String = oReturn("FreeSpace").ToString()
If Left(oReturn("Name").ToString(), 1) = "Y" Then
Console.WriteLine(sFreespace)
End If
Next
Why not just make your WMI query only pull back where name='Y'?
So:
Dim oQuery As System.Management.ObjectQuery = New System.Management.ObjectQuery("select FreeSpace,Size,Name from Win32_LogicalDisk where DriveType=3 AND name='Y'")