check connection sharing network folder using username and password - vb.net

In my application check network folder connection using following code
Dim myIP As IPHostEntry = Dns.GetHostEntry(txtNetworkDrive.Text.Trim.Split("\", options:=StringSplitOptions.RemoveEmptyEntries)(0))
Dim IPAddress As String = myIP.AddressList.GetValue(0).ToString
Dim xStr As New System.Security.SecureString
For Each c As Char In txtNetworkPassword.Text.Trim
xStr.AppendChar(c)
Next
Dim psi As New ProcessStartInfo()
psi.UserName = txtNetworkusername.text
psi.Password = xStr
psi.Domain = IPAddress
psi.FileName = txtNetworkDrive.Text
psi.UseShellExecute = False
Process.Start(psi)
The Input like
Network drive = "\\Sys4\shareddocs"
Network password= "sys4"
Network Username="user"
IPaddress="198.168.0.24"
But all time it show login failure bad username and password. what am doing wrong?
How get the solutions?

Related

VB NET Read Remote Registry

I'm trying to get the architecture and the operating system of many remote pcs.
In order to do that i'm querying Win32_OperatingSystem and parsing the "Caption" for the O.S. and for the architecture im reading OSArchitecture .
In Windows XP this value does not exists, so i thought that reading the HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment\PROCESSOR_ARCHITECTURE
would have done the trick like this code:
Try
Dim co As New ConnectionOptions
co.Impersonation = ImpersonationLevel.Impersonate
co.Authentication = AuthenticationLevel.PacketPrivacy
co.EnablePrivileges = True
co.Username = username
co.Password = password
Dim scope As New ManagementScope("\\" & machine.Text & "\root\cimv2", co)
scope.Connect()
Dim environmentKey, asd2 As Microsoft.Win32.RegistryKey
Dim asd As String
environmentKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, machine.Text)
asd2 = environmentKey.OpenSubKey("SYSTEM\CurrentControlSet\Control\Session Manager\Environment", True)
asd = asd2.GetValue("PROCESSOR_ARCHITECTURE")
Debug.Print("asd: " + asd)
environmentKey.Close()
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
My problem is: if im trying this code I get an System.Security.SecurityException: "Accessing remote registry not permitted"
I am, and i know the administrator username and password.
In fact if I run a simple cmdkey /add:targetname /user:username /pass:password
It works.
So why do I have to run a cmdkey /add even if i have alredy specified the username and password in the ConnectionOptions ??
P.S. Sorry for my bad English
This may very well be because remote registry access is not enabled on the target PC.
Even if you know the administrator credentials, remote access to the registry will not work if the feature isn't enabled on the target PC.
To enable it, see the following Microsoft Knowledge Base Article, which covers a variety of Windows Operating Systems: https://support.microsoft.com/en-us/kb/314837
All right, i got it:
Const HKEY_current_user As String = "80000002"
Dim options As New ConnectionOptions
options.Impersonation = ImpersonationLevel.Impersonate
options.EnablePrivileges = True
options.Username = ".\administrator"
options.Password = "my_password"
Dim myScope As New ManagementScope("\\" & RemotePCHostname & "\root\default", options)
Dim mypath As New ManagementPath("StdRegProv")
Dim mc As New ManagementClass(myScope, mypath, Nothing)
Dim inParams As ManagementBaseObject = mc.GetMethodParameters("GetDWORDValue")
inParams("hDefKey") = UInt32.Parse(HKEY_current_user,System.Globalization.NumberStyles.HexNumber) 'RegistryHive.LocalMachine
inParams("sSubKeyName") = "SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
inParams("sValueName") = "PROCESSOR_ARCHITECTURE"
Dim outParams As ManagementBaseObject = mc.InvokeMethod("GetStringValue", inParams, Nothing)
If (outParams("ReturnValue").ToString() = "0") Then
MessageBox.Show(outParams("sValue").ToString())
Else
MessageBox.Show("Error retrieving value : " + outParams("ReturnValue").ToString())
End If

Authenticating to Web Service VB.Net

Hi I am trying to Authenticate to my web service and missing something..
My Service reference is called - MBSDKServiceLD
My Web Reference is called - LANDeskMBSDK
I have these connected in Visual Studio 2013 And are resolving methods in the code
Here is my code for the authentication but its not complete..
Option Explicit On
Imports System.Net
Dim objFSO As Object
Dim objExec As Object
Dim objNetwork As Object
Dim strComputer As String
Dim strUser As String
Dim User As String
Dim Password As String
Dim Domain As String
Dim URL As String
Dim Cred As String
Dim strTaskName As String
Dim strPackageName As String
Dim strDeliveryMethod As String
Dim strCustomGroup As String
Dim boolStartNow As Boolean
Dim WakeUpMachines As Boolean
Dim boolCommonTask As Boolean
Dim strAutoSync As String
Dim TaskID As String
Dim strConnection As New System.Data.SqlClient.SqlConnection
Dim LDWebService
Dim intTaskID As String
Dim LDService As Object
Dim strDeviceName As String
Sub RunLANDeskTask(ByVal sender As Object, ByVal LDService As MBSDKServiceLD.MBSDKSoap)
End Sub
Sub CreateTask
User = "username1"
Password = "password1"
Domain = "domain1"
URL = "http://myserver/MBSDKService/MsgSDK.asmx?WSDL"
Dim MyCredentails As New System.Net.CredentialCache()
Dim NetCred As New System.Net.NetworkCredential(User, Password, Domain)
MyCredentails.Add(New Uri(URL), "Basic", NetCred)
strPackageName = "Adobe Acrobat XI PRO"
strDeliveryMethod = "Standard push distribution"
Dim strTargetDevice As String
strTargetDevice = Nothing
strTaskName = strPackageName & " - " & DateTime.Now & " -Provisioning Task for" & " " & strComputer
Try
RunLANDeskTask(LANDeskMBSDK, LDService.CreateTask(strTaskName, strDeliveryMethod, strPackageName, False, False, strAutoSync).TaskID)
Catch ex As Exception
MsgBox("Error creating task")
End Try
End Sub
What comes after this part or have i got this totally wrong?
When I type LDService. I see all the methods so I am connecting to the reference in VS but not authenticating.
It should really be as simple as this (sorry it's in c#):
MyWebService svc = new MyWebService();
svc.Credentials = new System.Net.NetworkCredential(UserID, pwd);
bool result = svc.MyWebMethod();
The following might be helpful:
This is quite old, but the comments are good.
I've just found the following on MSDN, which looks like what you want:
localhost.Sample svc = new localhost.Sample();
try {
CredentialCache credCache = new CredentialCache();
NetworkCredential netCred =
new NetworkCredential( "Example", "Test$123", "sseely2" );
credCache.Add( new Uri(svc.Url), "Basic", netCred );
svc.Credentials = credCache;
Ok i got this working... But i have to run the code under an account that can access the Web service -
Dim URL As String = "http://server/MBSDKService/MsgSDK.asmx?WSDL"
Dim myService As New LANDeskMBDSK.MBSDK
myService.Url = URL
Dim CredCache As New System.Net.CredentialCache
CredCache.Add(New Uri(myService.Url), "Basic", Cred)
myService.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials

How to impersonate an account and start explorer.exe?

I have the following code. Which results in error The application was unable to start correctly (0xc0000142). Click OK to close the application. Can someone tell me what is wrong?
Dim domain, username, passwordStr, remoteServerName As String
Dim password As New Security.SecureString
Dim command As New Process
domain = DBc.GetControlVal(34) 'Domain Name
username = DBc.GetControlVal(35) 'Network username
passwordStr = ENDC.DecryptData(DBc.GetControlVal(36)) 'password
remoteServerName = DBc.GetControlVal(37) 'Remote server Name
Dim impersonator As New clsAliasAccount(username, passwordStr)
For Each c As Char In passwordStr.ToCharArray
password.AppendChar(c)
Next
command.StartInfo.FileName = "C:\Windows\explorer.exe"
command.StartInfo.Arguments = "\\" & remoteServerName & "\"
command.StartInfo.UserName = username
command.StartInfo.Password = password
command.StartInfo.Domain = domain
command.StartInfo.Verb = "open"
command.StartInfo.UseShellExecute = False
impersonator.BeginImpersonation()
command.Start()
impersonator.EndImpersonation()

How to run batch commands with dynamic statements?

I am writing code in VB.NET 2.0 and want to run batch commands for FTP using FTP -s:filename command.
I have a Batch file FTP.TXT for FTP Upload. It has the following statements:
OPEN <FPT SERVER IP>
USERNAME
PASSWORD
ASC
CD FOLDERNAME
PUT D:\DRFT000009.TXT FTPDRFTIN.DRFT000009
BYE
I have to dynamically change the filename in the Batch File. Now either I can create a Batch file at runtime and then read it or I got a code to set the input stream of the Process object. But its not working as desired.
This code runs fine but here I read a static batch file FTP.TXT from the computer:
Public Sub FTP4()
Dim psi As ProcessStartInfo
Dim totalerror As String = ""
psi = New ProcessStartInfo()
psi.FileName = "FTP.EXE"
psi.Arguments = " -s:D:\FTP.TXT"
psi.RedirectStandardError = True
psi.RedirectStandardOutput = True
psi.CreateNoWindow = True
psi.WindowStyle = ProcessWindowStyle.Hidden
psi.UseShellExecute = False
Dim process As Process = process.Start(psi)
Dim error2 As String = process.StandardError.ReadToEnd()
totalerror = totalerror & error2
process.WaitForExit()
Response.Write(totalerror)
End Sub
But I want somehow to get the FTP done with custom file name for each request. This is what I tried which is not working:
Public Sub FTP5()
Dim totalerror As String = ""
Dim BatchScriptLines(6) As String
Dim process As New Process
process.StartInfo.FileName = "FTP.EXE"
process.StartInfo.UseShellExecute = False
process.StartInfo.CreateNoWindow = True
process.StartInfo.RedirectStandardInput = True
process.StartInfo.RedirectStandardOutput = True
process.StartInfo.RedirectStandardError = True
process.Start()
process.BeginOutputReadLine()
Using InputStream As System.IO.StreamWriter = process.StandardInput
InputStream.AutoFlush = True
BatchScriptLines(0) = "OPEN <FPT IP ADDRESS>"
BatchScriptLines(1) = "USERNAME"
BatchScriptLines(2) = "PASSWORD"
BatchScriptLines(3) = "ASC"
BatchScriptLines(4) = "CD SFCD40DAT"
BatchScriptLines(5) = "PUT D:\DRFT000006.TXT FTPDRFTIN.DRFT000006"
BatchScriptLines(6) = "BYE"
For Each ScriptLine As String In BatchScriptLines
InputStream.Write(ScriptLine & vbCrLf)
Next
End Using
Dim error2 As String = process.StandardError.ReadToEnd()
totalerror = totalerror & error2
process.WaitForExit()
Response.Write(totalerror)
End Sub
Please advise how I can get the "FTP -s:filename" command executed in this case. Basically I want to do something similar to single line batch file execution which I not able to do.
Being a simple text file with a clear format, you could rewrite the file passing the parameters that need to be dynamically changed
Public Sub FTP4()
' Of course I assume that, at this point your program knows the exact values '
' to pass at the procedure that rebuilds the file'
PrepareFTPFile("D:\DRFT000006.TXT", "USERNAME", "PASSWORD")
' Now you call the original code.....
Dim psi As ProcessStartInfo
Dim totalerror As String = ""
psi = New ProcessStartInfo()
psi.FileName = "FTP.EXE"
psi.Arguments = " -s:D:\FTP.TXT"
....
End Sub
Public Sub PrepareFTPFile(fileToUpload as String, username as string, userpass as string)
Using sw = new StreamWriter("D:\FTP.TXT", False)
sw.WriteLine("OPEN <FPT IP ADDRESS>")
sw.WriteLine(username)
sw.WriteLine(userpass)
sw.WriteLine("ASC")
sw.WriteLine("CD SFCD40DAT")
sw.WriteLine("PUT " + fileToUpload + " FTPDRFTIN." + Path.GetFileNameWithoutExtension(fileToUpdload))
sw.WriteLine("BYE")
End Using
End Sub

ftp file transfer using vb.net without any third party tools

I am writing the code using vb.net for file transfer from remote machine to local machine with out using any third party tools
This my code
Dim reqFTP As FtpWebRequest
Dim filepath As String
Dim filename As String
Dim filename1 As String
Dim ftpserverip As String
Dim ftpuserid As String
Dim ftpPassword As String
Try
filename1 = TxtRemoteFile.Text
filepath = TxtLocalFile.Text
filename = Locfname.Text
ftpserverip = TxtServerIP.Text
ftpuserid = TxtUserName.Text
ftpPassword = TxtPwd.Text
Dim outputStream As FileStream = New FileStream((filepath + ("\\" + filename)), FileMode.Create)
reqFTP = CType(FtpWebRequest.Create(New Uri(("ftp://" _
+ (ftpserverip + ("/" + filename1))))), FtpWebRequest)
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile
reqFTP.UseBinary = True
reqFTP.Credentials = New NetworkCredential(ftpuserid, ftpPassword)
Dim response As FtpWebResponse = CType(reqFTP.GetResponse, FtpWebResponse)
outputStream.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
but am getting error like" remote server returned error :(550) fi
I had the same issue. I was not including httpdocs in the remote path.
Example:
ftp://ftp.websitename.com/httpdocs/filenametocopy.txt
System.Net.WebRequest.Create("ftp://ftp.websitename.com/httpdocs/filenametocopy.txt")
Permission was denied because i was trying to write the file outside the root directory.