I have created an asp.net webpage and from the webpage I am using the code below to establish a remote desktop connection.
rdp.exe is a external file
Here is my code
Protected Sub BtnRemote_Click(ByVal sender As Object, ByVal e As EventArgs) Handles BtnRemote.Click
Dim Process As New System.Diagnostics.Process
Dim startinfo As New System.Diagnostics.ProcessStartInfo
startinfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal
startinfo.FileName = "C:\WINDOWS\system32\cmd.exe"
Dim path = "D:\rdp.exe"
startinfo.Arguments = path + "/v:" + txtTerminal.Text + " " + "/u:" + txtTerUser.Text + " " + "/p:" + txtTerPassword.Text
startinfo.UseShellExecute = False
Process.Start(startinfo)
End Sub
Everything is fine when I debug, but the system will not establish a remote connection.
But if I use the following command from command prompt, I am able to establish a remote connection.
E:\rdp /v:"IPAddress" /domain:"domain" /u:"username" /p:"password"
A problem i can see with this is within this line (Also Notice its got the Path, User, Password, and IP, BUT is missing the Domain Argument):
startinfo.Arguments = path + "/v:" + txtTerminal.Text + " " + "/u:" + txtTerUser.Text + " " + "/p:" + txtTerPassword.Text
as stated in your CMD arguments it needs to fit this format:
E:\rdp /v:"IPAddress" /domain:"domain" /u:"username" /p:"password"
However if you notice your startinfo.arguments doesn't contain a space in between the Directory and the IP Address Line so instead of reading it like this:
E:\rdp /v:"IPAddress" /u:"username" /p:"password"
it's reading it like this:
E:\rdp/v:"IPAddress" /u:"username" /p:"password"
just simply fix the line like this:
startinfo.Arguments = path + " /v:" + txtTerminal.Text + " /u:""" + txtTerUser.Text + """ /p:" + txtTerPassword.Text
I Also removed the Concatenations of + " " + because all you really need is a
space before the /'s and it will still work properly. Also notice that i have added extra quotes, because if the username supports spaces then when it goes to set the argument if the username contains a space then it will count them as two separate arguments quotes around it prevents it from being split into two different arguments
also instead of using CMD why not start the exe directly by
Dim p As Process
p.startinfo.FileName = "D:\rdp.exe"
p.StartInfo.WorkingDirectory = "D:\"
startinfo.Arguments = path + " /v:" + txtTerminal.Text + " /u:""" + txtTerUser.Text + """ /p:" + txtTerPassword.Text
p.Start()
Related
I run an application from PowerBuilder and terminate it when i dont need it. But the application when running, it executes other processes from a specific folder.
I want to kill all processes if they run from a specific folder.
How to get the process handles of all those processes that have specif folder name in their path?
Here an example to show how to terminate all running instance of Notepad.exe
OleObject wsh
integer li_rc
wsh = CREATE OleObject
wsh.ConnectToNewObject( "MSScriptControl.ScriptControl" )
wsh.language = "vbscript"
wsh.AddCode('function terminatenotepad() ~n ' + &
'strComputer = "." ~n ' + &
'Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2") ~n ' + &
'Set colItems = objWMIService.ExecQuery("Select * from Win32_Process where name = ~'notepad.exe~'") ~n ' + &
'For Each objItem in colItems ~n ' + &
' objItem.Terminate ~n ' + &
'Next ~n ' + &
'end function ~n ' )
wsh.executestatement('terminatenotepad()')
wsh.DisconnectObject()
DESTROY wsh
Try to change the where clause
where name = ~'notepad.exe~'" ...
for
where commandline = ~'" + ls_commandline + "~'" ...
where ls_commandline is the command line used to start your process.
See "Win32_Process class" for more infos.
/// This is simple code example Terminate a Running Process if here is specific
/// folder name in the path of the running program (\EagleGet\)
/// Two variable SelectThis and TheWhere can be changed to get different
/// results. Many things are not dynamic in this script and certainly not the
/// best way of writing code. but its just ok for a little quick work.`
OleObject wsh
Integer li_rc
String LineFeed = ' ~r~n '
String TheComputer = "." //local computer
String TheCode = "no need to set it here"
String FunctionName = "Whatever()" //any name you like
String SelectThis = "?" //only the columns/expressions
String TheWhere = "?" //only the where clause without keyword WHERE
String DoWhat = "?" //the action to perform for example 'Terminate' without quotes
String TheQuery = "no need to set here"
String WMIClass = "Win32_Process" /// The WMI class of running processes
String TheFolderName = "The folder name from which the creapy process is running (path) "
/// You just set DoWhat, SelectThis and TheWhere. Rest of the variables, you dont need to set here
/// SelectThis = is the columns or expressions you want returned by the Query
SelectThis = "*"
/// TheFolderName = set it to the name of the folder that exist in the path
///of the ruuning process you want to terminate
TheFolderName = "EagleGet"
/// TheWhere is the WHERE clause expressions
TheWhere = "ExecutablePath LIKE ~'%\\" + TheFolderName + "\\%~' "
/// DoWhat is the final function call of the WMI Class
DoWhat = "Terminate"
/// There is no need to chage anything from this point onward.
/// without double quotes, and you dont have to change TheQuery here
TheQuery = " SELECT " + SelectThis + " FROM " + WMIClass + " WHERE " + TheWhere
TheCode = "Function " + FunctionName + LineFeed + &
"strComputer = ~"" + TheComputer + "~"" + LineFeed + &
"Set objWMIService = GetObject(~"winmgmts:\\~" & strComputer & ~"\root\cimv2~")" + LineFeed + &
"Set colItems = objWMIService.ExecQuery(~"" + Trim(TheQuery) + "~" )" + LineFeed + &
"For Each objItem in colItems" + LineFeed + &
"objItem." + Trim(DoWhat) + LineFeed + &
"Next " + LineFeed + &
"END Function " + LineFeed
wsh = CREATE OleObject
wsh.ConnectToNewObject("MSScriptControl.ScriptControl")
wsh.Language = "VBScript"
wsh.AddCode(TheCode)
TRY
wsh.ExecuteStatement(FunctionName)
CATCH (RunTimeError Re01)
MessageBox("Query Error", "Following code has some problems.~r~n~r~n" + TheCode, StopSign!)
END TRY
wsh.DisconnectObject()
DESTROY wsh
i'm writing a little utility for my job, i need to change the actual machine name into serial number of the machine, i already found how to get serial number but i have no idea how to set the machine name and every solution i have tried haven't worked, someone have some suggestions?
Dim q As New SelectQuery("Win32_bios")
Dim search As New ManagementObjectSearcher(q)
Dim info As New ManagementObject
Try
For Each info In search.Get
Call MessageBox.Show("Serial Number: " & info("serialnumber").ToString +
vbCrLf + "Machine Name : " + Environment.MachineName)
Next
Return 1
Catch err As ManagementException
Call MessageBox.Show("Error: " & err.Message)
Return -99
End Try
I found a solution
Dim p As Process = New Process()
Dim pi As ProcessStartInfo = New ProcessStartInfo()
pi.Verb = "Runas"
pi.WindowStyle = ProcessWindowStyle.Hidden
pi.Arguments = "/K WMIC computersystem where caption='" + Environment.MachineName + "' rename Prova"
pi.FileName = "cmd.exe"
pi.UseShellExecute = True
pi.CreateNoWindow = True
Process.Start(pi)
It's just an utility for me but there is a way if i don't want ask the permission to run the process?
My script automatically uploads a text file after being created and editted through the program. The creating and editting (appending) works fine, but when the exe reaches the line where the file is uploaded, I get the error:
Cannot access file because used by another process
The file is being closed and disposed before uploading, but that doesn't matter. Even after some google searches I can't find the problem and solution.
I use the following code to create and append the text.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles BtnAdd.Click
Try
Using file As New System.IO.StreamWriter(currentdir + "\logs\" + FormClient.gametitle + "." + FormLogin.username + "_" + thisDate + "_ [" + fileNumber + "]" + ".txt", True)
file.WriteLine(TxtIssue.Text + " " + TxtWhen.Text + " " + TxtWhere.Text + " " + TxtInfo.Text)
file.WriteLine("")
End Using
Catch ex As Exception
MessageBox.Show(("Error while loading: " + ex.Message))
End Try
End Sub
Private Sub FormFeedback_Closing(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles MyBase.FormClosing
thisDate = Today
Dim filenameFormat = currentdir + "\logs\" + FormClient.gametitle + "." + FormLogin.username + "_" + thisDate + "_ [" + fileNumber + "]" + ".txt"
Dim uploadFormat = Path.Combine("-removed-", filenameFormat)
My.Computer.Network.UploadFile(filenameFormat, uploadFormat, "mennovv", "mennomail98", True, 500)
End Sub
The following piece of code checks if a file exists, but I don't think this is the problem.
While My.Computer.FileSystem.FileExists(currentdir + "\logs\" + FormClient.gametitle + "." + FormLogin.username + "_" + thisDate + "_ [" + fileNumber + "]" + ".txt") = True
fileNumber += 1
End While
I have the following VB.NET 4.0 console application that runs 7z.exe in a process and successfully completes with a zipped file:
Public Sub CompressFiles(sZipFileName As String, sDriveLetter As String)
Dim s7ZipCmdArgs As String = ""
Dim myProcess As New Process
Console.WriteLine()
Console.WriteLine("Scanning files...")
'Compress files
s7ZipCmdArgs = " a -r -y -xr!windows\ -xr!$Recycle.Bin\ " + sZipFileName _
+ " " + sDriveLetter + "\*.txt" _
+ " " + sDriveLetter + "\*.doc" _
+ " " + sDriveLetter + "\*.xls" _
+ " " + sDriveLetter + "\*.ppt" _
+ " " + sDriveLetter + "\*.url" _
+ " " + sDriveLetter + "\*.docx" _
+ " " + sDriveLetter + "\*.xlsx" _
+ " " + sDriveLetter + "\*.pptx" _
+ " " + sDriveLetter + "\*.pdf" _
+ " " + sDriveLetter + "\*.wav" _
+ "> C:\test\zipresults.txt"
myProcess.StartInfo.FileName = "C:\test\7-Zip\7z.exe"
myProcess.StartInfo.Arguments = s7ZipCmdArgs
myProcess.StartInfo.WorkingDirectory = "C:\test"
myProcess.StartInfo.UseShellExecute = False
myProcess.StartInfo.CreateNoWindow = True
myProcess.Start()
myProcess.WaitForExit()
End Sub
The code executes fine except for the redirect to a text file: "> C:\test\zipresults.txt" in the s7ZipCmdArgs string variable. I'm not sure why that's not working, I've tried different sets of double and triple quotes without success. It does work in a batch file using the same string.
My second question is: How do I capture the 7Zip exit code so that I can determine if it completed successfully? It returns the following integers: 0 (No errors), 1 (Non fatal error), 2 (Fatal error), 7 (Command line error), 8 (Memory error), and 255 (User error). I'm not sure how to capture the integer so that I can decode it.
For the first part, have you tried adding a space before the > in your command args? You could also check out this answer for capturing the output in code.
For the first part, per this answer you can't redirect the standard output using > when using Process.Start(). So, you will need to remove the redirect from the arguments, set StartInfo.RedirectStandardOutput to true, and then write the output to a file in the OutputDataReceived event. Something like this:
Dim pgm = "C:\Program Files\7-Zip\7z.exe"
Dim args = "l C:\Dev\Test.zip"
Dim myProcess = New Process()
With myProcess.StartInfo
.FileName = pgm
.Arguments = args
.WorkingDirectory = "C:\Dev"
.UseShellExecute = False
.CreateNoWindow = True
.RedirectStandardOutput = True
End With
Using out = New StreamWriter("C:\Dev\test.txt")
AddHandler myProcess.OutputDataReceived,
Sub(sender, e)
out.WriteLine(e.Data)
End Sub
myProcess.Start()
myProcess.BeginOutputReadLine()
myProcess.WaitForExit()
End Using
For the second, myProcess.ExitCode will have the result after the WaitForExit() call.
I am trying to run the shadow command in cmd.exe from my VB program but for some reason it will not run the command I have tried a few different things all of which have not worked. I was able to save the command to a batch file and then execute it with success but I would prefer to pass the argument/command to command prompt directly and execute this way. Basically, I have a the user run another program I created to extract sessionid and server name (I then just take the server number off the end). They get a 4 digit passcode on their end that is essentially first two is sessionid and last two are server number (all our servers are named ie smdts-(a number) so I just care about what server number they are on) I then take the four digit code and plug it into my shadow admin program. Here is my current code that doesn't work:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim SessId As String
Dim PassCode As String
Dim ServNum As String
Dim Prc As Process
PassCode = TextBox2.Text
SessId = PassCode.Substring(0, 2)
ServNum = PassCode.Substring(PassCode.Length - 2)
Dim fileargs As String = " shadow" + " " & SessId + " " + "/server:smdts-" + ServNum
Dim Pinfo = New System.Diagnostics.ProcessStartInfo
Pinfo.FileName = "cmd.exe"
Pinfo.Arguments = fileargs
Pinfo.ErrorDialog = False
Pinfo.UseShellExecute = False
Pinfo.CreateNoWindow = False
Pinfo.WindowStyle = ProcessWindowStyle.Normal
Pinfo.RedirectStandardOutput = False
Pinfo.RedirectStandardInput = True
Pinfo.RedirectStandardError = False
Prc = New Process
Prc.StartInfo = Pinfo
Prc.Start()
End Sub
What does work (batch file which I don't want to use):
Public Class Form1
Public pathvar As String = Environment.GetFolderPath(Environment.SpecialFolder.Personal)
Dim SessId As String
Dim PassCode As String
Dim ServNum As String
PassCode = TextBox2.Text
SessId = PassCode.Substring(0, 2)
ServNum = PassCode.Substring(PassCode.Length - 2)
Dim fileargs As String = " shadow" + " " & SessId + " " + "/server:smdts-" + ServNum
Dim Streamwriter As StreamWriter
Streamwriter = File.CreateText(pathvar + "\ShadowBatch.bat")
Streamwriter.WriteLine(fileargs)
Streamwriter.Close()
Shell(pathvar + "\ShadowBatch.bat")
End Sub
Any help on why the first example is not working would be GREATLY appreciated! Thanks!
Tom K
You're passing shadow ... as the arguments to CMD.
CMD does not support that.
Instead, you need to pass /c shadow ..., which will tell CMD to execute that command and exit.
Alternatively you could run shadow directly, without going through CMD.