I have been trying to connect remote PC with known Credentials but variable lon(refer below code) is showing Error-487.
Code:
Private Declare Function WNetAddConnection2 Lib "mpr.dll" Alias "WNetAddConnection2A" ( ByRef lpNetResource As NETRESOURCE, ByVal lpPassword As String, ByVal lpUserName As String, ByVal dwFlags As Integer) As Long
Private Declare Function WNetCancelConnection2 Lib "mpr.dll" Alias "WNetCancelConnection2A" (ByVal lpName As String, ByVal dwFlags As Long, ByVal fForce As Integer) As Long
Private Structure NETRESOURCE
Dim dwType As Long
Dim lpRemoteName As String
End Structure
Private Const RESOURCETYPE_DISK = &H1
Private Sub ConnectToPC()
Dim networkResource As New NETRESOURCE
Dim lon As Long
With networkResource
.dwType = RESOURCETYPE_DISK
.lpRemoteName = "\\192.168.1.1"
End With
lon = WNetAddConnection2(networkResource, "123", "ADMIN", 0)
msgbox(lon)
lon = WNetCancelConnection2("\\192.168.1.1", 0, 1)
msgbox(lon)
End Sub
Tried Below thing but it didn't serve my purpose
- Change type from Integer to Int32/Int64
I have been working on this issue for last two days but couldn't gain any success. Can anybody tell me what went wrong with code? Any help will be highly Appreciated
Related
I am just learning programming, so please be understanding :)
I am writing an application that needs to send text data to another console program. I was successful with SendMessage(), but unfortunately with Wine (on linux) it is not supported for console applications.
So I found a function that is supported. This is WriteConsoleInput().
Here is my code, could someone indicate why it doesn't work?
Public Declare Function AttachConsole Lib "kernel32" (ByVal ProcessID As Long) As Boolean
Private Declare Function GetStdHandle Lib "kernel32.dll" (ByVal nStdHandle As Int32) As IntPtr
Declare Function WriteConsoleInputW Lib "kernel32" Alias "WriteConsoleInputW" (ByVal hConsoleInput As Integer, ByVal lpBuffer As String, ByVal nNumberOfCharsToWrite As Integer, ByRef lpNumberOfCharsWritten As Integer) As Integer
Declare Function WriteConsoleInputA Lib "kernel32" Alias "WriteConsoleInputA" (ByVal hConsoleInput As Integer, ByVal lpBuffer As String, ByVal nNumberOfCharsToWrite As Integer, ByRef lpNumberOfCharsWritten As Integer) As Integer
Declare Function SetConsoleTitle Lib "kernel32.dll" Alias "SetConsoleTitleA" (lpConsoleTitle As String) As Boolean
Private Const STD_OUTPUT_HANDLE As Long = -11&
Private Const STD_INPUT_HANDLE As Long = -10&
Private Const STD_ERROR_HANDLE As Long = -12&
Private Const INVALID_HANDLE_VALUE As Long = -1&
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim titleStr As String = "Test"
Dim textToWrite As Char() = CType("test", Char())
Dim stdIN As Integer
Dim stdOUT As Integer
Dim charwritten As Integer = 0
Dim ret As Integer
If ReturnCMDProcessID() = 0 Then
MessageBox.Show("CMD off")
Exit Sub
End If
AttachConsole(ReturnCMDProcessID())
stdIN = CInt(GetStdHandle(CInt(STD_INPUT_HANDLE)))
stdOUT = CInt(GetStdHandle(CInt(STD_OUTPUT_HANDLE)))
ret = WriteConsoleInputA(stdIN, textToWrite, textToWrite.Length, charwritten)
SetConsoleTitle(titleStr)
End Sub
Did you try the "built-in" way to do this?
System.Console:
https://learn.microsoft.com/en-us/dotnet/api/system.console?view=netframework-4.8
And in particular Console.In
https://learn.microsoft.com/en-us/dotnet/api/system.console.in?view=netframework-4.8
And Console.Out
https://learn.microsoft.com/en-us/dotnet/api/system.console.out?view=netframework-4.8
I also just noticed you are setting the title, that is as simple as Console.Title = "My Title"
I have been trying to connect remote PC(with known credentials and on the same network) to my PC with vb.net but struck at following Error:
Managed Debugging Assistant 'PInvokeStackImbalance' : 'A call to PInvoke function 'WindowsApp1!WindowsApp1.Form1::WNetAddConnection2' has unbalanced the stack. This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature.'
Whereas same code has been executed flawlessly in Vb6.
Code:
Private Declare Function WNetAddConnection2 Lib "mpr.dll" Alias "WNetAddConnection2A" (lpNetResource As NETRESOURCE, ByVal lpPassword As String, ByVal lpUserName As String, ByVal dwFlags As Long) As Long
Private Declare Function WNetCancelConnection2 Lib "mpr.dll" Alias "WNetCancelConnection2A" (ByVal lpName As String, ByVal dwFlags As Long, ByVal fForce As Long) As Long
Private Structure NETRESOURCE
Dim dwType As Long
Dim lpRemoteName As String
End Structure
Private Const RESOURCETYPE_DISK = &H1
Private Sub ConnectToPC()
Dim networkResource As New NETRESOURCE
Dim lon As Long
With networkResource
.dwType = RESOURCETYPE_DISK
.lpRemoteName = "\\192.168.1.1"
End With
lon = WNetAddConnection2(networkResource, "123", "ADMIN", 0)
End Sub
Exception is thrown at lon and code coudn't execute further.
I am new to VB.net language.Any assistance would be very helpful.
From JQSOFT's comment:
In the signature replace (lpNetResource As NETRESOURCE, ...
with
(ByRef lpNetResource As NETRESOURCE, ... because the NETRESOURCE here is a
structure and not a class. Also, replace any Long with Integer
So i have the following code
Imports System.Diagnostics
Imports System.IO
Imports System.Runtime.InteropServices
Public Class Form1
<StructLayout(LayoutKind.Sequential)> _
Structure OSVERSIONINFO
Dim dwOSVersionInfoSize As Integer
Dim dwMajorVersion As Integer
Dim dwMinorVersion As Integer
Dim dwBuildNumber As Integer
Dim dwPlatformId As Integer
<MarshalAs(UnmanagedType.ByValTStr, SizeConst:=128), VBFixedString(128)> Dim szCSDVersion As String
End Structure
<StructLayout(LayoutKind.Sequential)> _
Structure MEMORY_BASIC_INFORMATION
Dim BaseAddress As Integer
Dim AllocationBase As Integer
Dim AllocationProtect As Integer
Dim RegionSize As Integer
Dim State As Integer
Dim Protect As Integer
Dim lType As Integer
End Structure
<StructLayout(LayoutKind.Sequential)> _
Structure SYSTEM_INFO ' 36 Bytes
Dim dwOemID As Integer
Dim dwPageSize As Integer
Dim lpMinimumApplicationAddress As Integer
Dim lpMaximumApplicationAddress As Integer
Dim dwActiveProcessorMask As Integer
Dim dwNumberOrfProcessors As Integer
Dim dwProcessorType As Integer
Dim dwAllocationGranularity As Integer
Dim wProcessorLevel As Short
Dim wProcessorRevision As Short
End Structure
Private Declare Function GetVersionEx Lib "kernel32" Alias "GetVersionExA" (ByRef LpVersionInformation As OSVERSIONINFO) As Integer
Private Declare Function VirtualQueryEx Lib "kernel32.dll" (ByVal hProcess As IntPtr, ByVal lpAddress As UInteger, ByRef lpBuffer As MEMORY_BASIC_INFORMATION, ByVal dwLength As Integer) As Integer
Private Declare Sub GetSystemInfo Lib "kernel32" (ByRef lpSystemInfo As SYSTEM_INFO)
Private Declare Function OpenProcess Lib "kernel32" (ByVal dwDesiredAccess As Integer, ByVal blnheritHandle As Integer, ByVal dwAppProcessId As Integer) As Integer
Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Integer) As Integer
Private Declare Function ReadProcessMemory Lib "kernel32" (ByVal hProcess As Integer, ByRef lpBaseAddress As Integer, ByRef lpBuffer As Long, ByVal nSize As Integer, ByRef lpNumberOfBytesWritten As Integer) As Integer
Private Declare Function WriteProcessMemory Lib "kernel32" (ByVal hProcess As Integer, ByRef lpBaseAddress As Integer, ByRef lpBuffer As String, ByVal nSize As Integer, ByRef lpNumberOfBytesWritten As Integer) As Integer
Private Declare Function GetWindowThreadProcessId Lib "user32" (ByVal hWnd As Integer, ByRef lpdwProcessId As Integer) As Integer
Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As Integer, ByVal lpWindowName As Integer) As Integer
Private Declare Function GetParent Lib "user32" (ByVal hWnd As Integer) As Integer
Private Declare Function GetWindow Lib "user32" (ByVal hWnd As Integer, ByVal wCmd As Integer) As Integer
Private Const PROCESS_VM_READ = (&H10)
Private Const PROCESS_VM_OPERATION = (&H8)
Private Const PROCESS_QUERY_INFORMATION = (&H400)
Public Const PROCESS_READ_WRITE_QUERY = PROCESS_VM_READ + PROCESS_VM_OPERATION + PROCESS_QUERY_INFORMATION
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim pid As Integer, hProcess As Integer
Dim lpMem As Integer, ret As DialogResult, lLenMBI As Integer
Dim lWritten As Integer
Dim sBuffer As String
Dim sSearchString As String = "", sReplaceString As String = ""
Dim si As SYSTEM_INFO
Dim mbi As MEMORY_BASIC_INFORMATION
For Each p As Process In Process.GetProcesses
If p.ProcessName = "notepad" Then
pid = p.Id
End If
Next
hProcess = OpenProcess(PROCESS_READ_WRITE_QUERY, False, pid)
lLenMBI = Len(mbi)
'Determine applications memory addresses range
GetSystemInfo(si)
lpMem = si.lpMinimumApplicationAddress
Do While lpMem < si.lpMaximumApplicationAddress
mbi.RegionSize = 0
ret = VirtualQueryEx(hProcess, lpMem, mbi, lLenMBI)
If ret = lLenMBI Then
If ((mbi.lType = &H20000) And (mbi.State = &H1000)) Then
If mbi.RegionSize > 0 Then
Dim stringinmemory As Long
sBuffer = mbi.RegionSize
ReadProcessMemory(hProcess, mbi.BaseAddress, stringinmemory, mbi.RegionSize, lWritten)
Debug.WriteLine(sBuffer)
End If
End If
lpMem = mbi.BaseAddress + mbi.RegionSize
Else
Exit Do
End If
Loop
CloseHandle(hProcess)
End Sub
End Class
And it should read all notepad memory (step by step like). I get no errors when i run it , but it returns
4096
4096
4096
8192
90112
4096
344064
131072
8192
45056
172032
4096
155648
4096
This code works well in VB6, but i converted it to VB.NET.
What am I doing wrong ? Can you help me please ?
Thanks in advance.
Nicu
You are printing the value of sBuffer which is an integer which explains the results you are seeing. Besides, sBuffer does not contain the data which is read from memory. I think your lpBuffer parameter (and also stringinmemory as well) should not be a Long but instead be an Byte array. Something like this:
Const PROCESS_WM_READ As Integer = &H10
<DllImport("kernel32.dll")> _
Public Shared Function OpenProcess(dwDesiredAccess As Integer, bInheritHandle As Boolean, dwProcessId As Integer) As IntPtr
End Function
<DllImport("kernel32.dll")> _
Public Shared Function ReadProcessMemory(hProcess As Integer, lpBaseAddress As Integer, lpBuffer As Byte(), dwSize As Integer, ByRef lpNumberOfBytesRead As Integer) As Boolean
End Function
Public Shared Sub Main()
Dim notepadProcess As Process = Process.GetProcessesByName("notepad")(0)
Dim processHandle As IntPtr = OpenProcess(PROCESS_WM_READ, False, notepadProcess.Id)
Dim bytesRead As Integer = 0
Dim buffer As Byte() = New Byte(23) {}
'The address in this line is hard-coded. Use whatever is appropriate for your situation.
ReadProcessMemory(CInt(processHandle), &H36B9D0, buffer, buffer.Length, bytesRead)
Console.WriteLine(Encoding.Unicode.GetString(buffer))
Console.ReadLine()
End Sub
I need to first map and then later unmap 2x drives using VB.NET.
When mapping the drives, I also need to pass a username and password (as not all users have admin access).
However, not only is the below not working (failing to map, so in turn failing to unmap), but I notice that I only have the option to pass a password when mapping a drive, not a username.
Can anyone help me in fixing these problems? Thanks.
Private Declare Function WNetAddConnection Lib "mpr.dll" Alias "WNetAddConnectionA" (ByVal lpszNetPath As String,
ByVal lpszPassword As String,
ByVal lpszLocalName As String) As Long
Private Declare Function WNetCancelConnection Lib "mpr.dll" Alias "WNetCancelConnectionA" (ByVal lpszName As String,
ByVal bForce As Long) As Long
Public Function MapDrive(ByVal UNCPath As String, ByVal Password As String, ByVal DriveLetter As String) As Boolean
Dim MappedResult As Long = WNetAddConnection(UNCPath, Password, DriveLetter)
Return IIf(MappedResult = 0, True, False)
End Function
Public Function UnmapDrive(ByVal DriveLetter As String) As Boolean
Dim UnmappedResult As Long = WNetCancelConnection(DriveLetter, 0)
Return IIf(UnmappedResult = 0, True, False)
End Function
You should switch to using the WNetAddConnection2/WNetCancelConnection2 functions. The former allows you to specify a username in the call. Here are the PInvoke signatures I've used successfully in the past:
Private Declare Function WNetAddConnection2 Lib "mpr.dll" Alias "WNetAddConnection2A" _
(ByRef lpNetResource As NETRESOURCE, ByVal lpPassword As String, _
ByVal lpUserName As String, ByVal dwFlags As Integer) As Integer
Private Declare Function WNetCancelConnection2 Lib "mpr.dll" Alias "WNetCancelConnection2A" _
(ByVal lpName As String, ByVal dwFlags As Integer, ByVal fForce As Integer) As Integer
Private Declare Function WNetGetLastError Lib "mpr.dll" Alias "WNetGetLastErrorA" _
(ByRef nError As Integer, ByRef lpErrorBuf As String, ByVal nErrorBufSize As Integer, _
ByRef lpNamebuf As String, ByVal nNameBufSize As Integer) As Integer
<StructLayout(LayoutKind.Sequential)> _
Public Structure NETRESOURCE
Public dwScope As Integer
Public dwType As Integer
Public dwDisplayType As Integer
Public dwUsage As Integer
Public lpLocalName As String
Public lpRemoteName As String
Public lpComment As String
Public lpProvider As String
End Structure
Private Const ForceDisconnect As Integer = 1
Private Const RESOURCETYPE_DISK As Long = &H1
GetLastError is useful for figuring out why the mapping failed (bad password, etc).
I'm trying to find a simple way of checking user stats via FTP, wininet seems to be the best option.
How do I get the output from the command though?
Private Declare Function InternetCloseHandle Lib "wininet.dll" (ByVal HINet As Integer) As Integer
Private Declare Function InternetOpen Lib "wininet.dll" Alias "InternetOpenA" (ByVal sAgent As String, ByVal lAccessType As Integer, ByVal sProxyName As String, ByVal sProxyBypass As String, ByVal lFlags As Integer) As Integer
Private Declare Function InternetConnect Lib "wininet.dll" Alias "InternetConnectA" (ByVal hInternetSession As Integer, ByVal sServerName As String, ByVal nServerPort As Integer, ByVal sUsername As String, ByVal sPassword As String, ByVal lService As Integer, ByVal lFlags As Integer, ByVal lContext As Integer) As Integer
Public Declare Function ftpCommand Lib "wininet.dll" Alias "FtpCommandA" (ByVal hConnect As Integer, ByVal fExpectResponse As Boolean, ByVal dwFlags As Integer, ByVal lpszCommand As String, ByRef dwContext As Integer, ByRef phFtpCommand As Integer) As Boolean
Dim INet, INetConn As Integer
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
INet = InternetOpen("MyFTP", 1, vbNullString, vbNullString, 0)
INetConn = InternetConnect(INet, "192.168.1.6", 21, "user", "pwd", 1, 0, 0)
strCommand = "SITE SHOW SERVER 192.168.1.6.21"
Dim retv As Long
Dim Test = ftpCommand(INetConn, True, 2, strCommand, 0, retv)
Debug.Write(Test)
InternetCloseHandle(INetConn)
InternetCloseHandle(INet)
End Sub
The output I'm expecting is:
Response: 200- Server IP = "192.168.1.6"
Response: 200- Port = "21"
Response: 200- Start time = "10/02/2010 02:46:57 PM"
Response: 200- Download = "0.000 KB"
Response: 200- Upload = "0.000 KB"
Response: 200- Online Users = "0"
Response: 200-======================================
Response: 200 Site command OK
Thanks.
I think you may find use of InternetGetLastResponseInfo which is a link to the c++ definition
(found this by navigating the WinINet function list) but provides a useful hint
it says:
InternetGetLastResponseInfo Function
Retrieves the last error description or server response on the thread calling this function.
Consider this sample implementation
Private Function GetServerResponse() As String
Dim lError As Long
Dim strBuffer As String
Dim lBufferSize As Long
Dim retVal As Long
retVal = InternetGetLastResponseInfo(lError, strBuffer, lBufferSize)
strBuffer = New String("", lBufferSize + 1)
retVal = InternetGetLastResponseInfo(lError, strBuffer, lBufferSize)
GetServerResponse = strBuffer
End Function
Which calls the external function (here for copy paste access)
Declare Function InternetGetLastResponseInfo Lib "wininet" Alias "InternetGetLastResponseInfoA" (ByRef lpdwError As Long, ByVal lpszBuffer As String, ByRef lpdwBufferLength As Long) As Boolean
twice, once to get the buffer length and again to fill the buffer string then returns the filled buffer