How to run an exe by client remotely on server using vb6 - vb6

I'm using code below to execute my commands in cmd. Which is actually made for running an exe on my server.
Private Sub Command1_Click()
Dim FN As Integer
FN = FreeFile
'DOS COMMANDS
ServerName = "\\mydbserv"
ExePath = """d:\myfolder\my.exe"""
UserName = "myserver\myuser"
Password = "mypass"
MyCommand = "psexec " & ServerName & " -u " & UserName & " -p " & Password & " -i " & ExePath
'Open Bat file
Open "C:\Mybatc.bat" For Output As #FN
Print #FN, "cd c:\Users\myuser"
Print #FN, MyCommand
Print #FN, "Exit"
Close #FN
'Activate
result = Shell("C:\Mybatc.bat", vbHide)
End
End Sub
everything was fine until i seen that cmd is not getting closed when process is done.
and the worse is the exe i was trying to run remotely also not stops. When i check the cpu usage it always shows "00" doesnt even starts.. It shows like working for ever but never works actually.
So my question is :
Why i cant run this exe file remotely? (or why it just shows like running)
How can i remotely run and close when finished this exe file on server?
How can i close the window and process when finished on my pc as well?

How about this?
install Windbg on the server.
config the windbg auto attach to your exe, when your exe is ready to running.
http://ask.brothersoft.com/image-file-execution-options-debugger-83827.html
running your script
after your exe is started, the windbg will attach to it.
input 'g' in the windbg command, let your exe to running.
wait until you think it should finished
ctrl-break to let the process hang on
input '~*kb' to windbg command, to see what's going on in every thread,
to find out why they are waiting, and what they are waiting for?

PSExec will only initiate the start of the process in a computer (most of the time remote), after that it has no control on the exe that is being executed. Kindly try to run it as a process (within a ProcessInfo as in C#)(with shell execute false). Also something like the following can be used to confirm the state of the process in remote PC:
Option Explicit
Private Sub Form_Load()
Dim strComputer As String
Dim sReturn As String
Dim strNameOfUser As Variant
Dim colProcesses As Object
Dim objProcess As Object
strComputer = "." '"." local or "\\ComputerName"
Set colProcesses = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2").ExecQuery("Select * from Win32_Process")
For Each objProcess In colProcesses
sReturn = objProcess.GetOwner(strNameOfUser)
If sReturn <> 0 Then
MsgBox "Could not get owner info for process " & objProcess.Name & vbNewLine & "Error = " & sReturn
Else
MsgBox "Process " & objProcess.Name & " is owned by " & "\" & strNameOfUser & "."
End If
Next
End Sub
link : http://www.vbforums.com/showthread.php?355203-RESOLVED-How-to-get-process-information
hope it helps

Related

PDFCreator COM Script Run as Service Fails to see Jobs Printed

I have a PDFCreator script I compiled in PrimalScript so that I could execute it via svrany and the problem I am running into is the fact that when I run the service the print jobs from the script are never seen by the queue. If I run the vbscript or the compiled exe from my session it works fine.
Here is the code in my vbs file that runs against pdfcreator version 2.1.1.820
Dim strExt, intStatus, strDestFileName, strInputFileName, strReason
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objShell = CreateObject("Shell.Application")
Set PDFCreatorQueue = CreateObject("PDFCreatorBeta.JobQueue")
strInputFileName = "C:\Temp\Test.txt"
strDestFileName = "C:\Temp\Test.pdf"
PDFProcess
' ** Sub Routine to render file as PDF
Sub PDFProcess
Dim objFolder, job, intStatPDFCreator, intPageCount
intPageCount = 1
WScript.Echo "PDF Destination Name: " & strDestFile
WScript.Echo "Initializing PDFCreator queue..."
intStatPDFCreator = PDFCreatorQueue.Initialize()
WScript.Echo "PDFCreator Object Status: " & intStatPDFCreator
If intStatPDFCreator = 0 Then
If Not objFSO.FileExists(strInputFileName) Then
WScript.Echo "PDFCreator: Can't find the file: " & strInputFileName
Else
WScript.Echo "Printing Page: " & strInputFileName
objShell.ShellExecute strInputFileName, "", "", "print"
WScript.Sleep 1000
WScript.Echo "Currently there are " & PDFCreatorQueue.Count & " job(s) in the queue"
End If
WScript.Echo "Waiting for the job to arrive at the queue..."
if Not(PDFCreatorQueue.WaitForJobs(intPageCount, 10)) Then
strReason = "The print job did not reach the queue within " & 10 & " seconds"
WScript.Echo strReason
intStatus = 0
Else
WScript.Echo "Currently there are " & PDFCreatorQueue.Count & " job(s) in the queue"
WScript.Echo "Getting job instance and merging"
PDFCreatorQueue.MergeAllJobs
while(PDFCreatorQueue.Count > 0)
Set job = PDFCreatorQueue.NextJob
WScript.Echo "Staging PDF File: " & strDestFileName
job.ConvertTo(strDestFileName)
WScript.sleep 5000
If Not(job.IsFinished Or job.IsSuccessful) Then
strReason = "Could not convert the file: " & strDestFileName
WScript.Echo strReason
intStatus = 0
Else
WScript.Echo "Job finished successfully"
End If
Wend
End If
WScript.Echo "Releasing the object"
PDFCreatorQueue.ReleaseCom()
Else
strReason = "Failed to create PDFCreator COM instance."
WScript.Echo strReason
intStatus = 0
End If
End Sub
The service I have running under my domain credentials and have modified the registry to allow it to run interactively
SERVICE_NAME: tgprintprocessor
TYPE : 110 WIN32_OWN_PROCESS (interactive)
STATE : 4 RUNNING
(STOPPABLE, PAUSABLE, ACCEPTS_SHUTDOWN)
WIN32_EXIT_CODE : 0 (0x0)
SERVICE_EXIT_CODE : 0 (0x0)
CHECKPOINT : 0x0
WAIT_HINT : 0x0
PID : 3752
FLAGS :
I have set interactive Services Detection to a running state.
reviewing the PDFCreator trace log I don't see any errors of any kind.
If I open PDFCreator printer and view the print queue, I do see the job hit the queue and exit, and can even pause the printer so the job stops in the printer queue but the com object queue is oblivious to its existence.
I also tried running PDFCreator.exe additionally as a service incase it needed to have an instance of the exe running in the background as I noticed the application itself does not fire up in task manager post print job submission like I typically see when executing the script manually.
What is my question, I guess I don't know where else to look and if there is maybe something I am missing that I can add to the above test script to attempt trapping the problem.
Resolution to this issue and behavior above is to change the driver isolation mode from the default NONE, to SHARED. I did this under Print Management Snapin. Took a while to figure it out....
If you are using WScript it will stop at the first wscript.echo. Make sure you are running with CScript.

Starting a process in VBS: path not found

I need to make a simple vbs script to run some process' automatically. I found the following script on microsoft's website. It works fine to run notepad.exe the way the original example shows, but I'm trying to modify it to run myprog.exe. The full path to this program is: C:\myprogdir\myprog.exe
Const SW_NORMAL = 1
strComputer = "."
strCommand = "myprog.exe"
strPath = "C:\myprogdir\"
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\cimv2")
' Configure the Notepad process to show a window
Set objStartup = objWMIService.Get("Win32_ProcessStartup")
Set objConfig = objStartup.SpawnInstance_
objConfig.ShowWindow = SW_NORMAL
' Create Notepad process
Set objProcess = objWMIService.Get("Win32_Process")
intReturn = objProcess.Create _
(strCommand, strPath, objConfig, intProcessID)
If intReturn <> 0 Then
Wscript.Echo "Process could not be created." & _
vbNewLine & "Command line: " & strCommand & _
vbNewLine & "Return value: " & intReturn
Else
Wscript.Echo "Process created." & _
vbNewLine & "Command line: " & strCommand & _
vbNewLine & "Process ID: " & intProcessID
End If
I keep getting Return value: 9, which indicates "Path Not Found". However the path is correct. Is there something I'm not getting?
You don't need all that to start a process, you just need the Shell object. Also, be sure to wrap the path of your executable in quotes (in case the path has spaces). Like this:
Option Explicit
Dim shl
Set shl = CreateObject("Wscript.Shell")
Call shl.Run("""C:\myprogdir\myprog.exe""")
Set shl = Nothing
WScript.Quit
Unless the path to your program is included in the system's %PATH% environment variable you need to specify the commandline with the full path to the executable. Specifying the path just as the working directory will not work.
strProgram = "myprog.exe"
strPath = "C:\myprogdir"
Set fso = CreateObject("Scripting.FileSystemObject")
strCommand = fso.BuildPath(strPath, strProgram)
...
intReturn = objProcess.Create(strCommand, strPath, objConfig, intProcessID)
Using the BuildPath method will save you the headaches caused by having to keep track of leading/trailing backslashes.
Note that you need to put double quotes around a path that contains spaces, e.g. like this:
strCommand = Chr(34) & fso.BuildPath(strPath, strProgram) & Chr(34)
As others have already pointed out, there are simpler ways to start a process on the local computer, like Run:
Set sh = CreateObject("WScript.Shell")
sh.Run strCommand, 1, True
or ShellExecute:
Set app = CreateObject("Shell.Application")
app.ShellExecute strCommand, , strPath, , 1
There are some notable differences between Run and ShellExecute, though. The former can be run either synchronously or asynchronously (which means the command either does or doesn't wait for the external program to terminate). The latter OTOH always runs asynchronously (i.e. the method returns immediately without waiting for the external program to terminate), but has the advantage that it can be used to launch programs with elevated privileges when UAC is enabled by specifying the verb "runas" as the 4th argument.
However, these methods only allow for launching processes on the local computer. If you want to be able to launch processes on remote computers you will have to use WMI:
strComputer = "otherhost"
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\cimv2")
See here for more information about WMI connections to remote hosts.

Run script in background

I want to run following script as scheduled task on Windows 7 in background. Now, script displays cmd window and, can I run script without visible cmd window?
Option Explicit
Dim WshShell, oExec
Dim RegexParse
Dim hasError : hasError = 0
Set WshShell = WScript.CreateObject("WScript.Shell")
Set RegexParse = New RegExp
Set oExec = WshShell.Exec("%comspec% /c echo list volume | diskpart.exe")
RegexParse.Pattern = "\s\s(Volume\s\d)\s+([A-Z])\s+(.*)\s\s(NTFS|FAT)\s+(Mirror|RAID-5)\s+(\d+)\s+(..)\s\s([A-Za-z]*\s?[A-Za-z]*)(\s\s)*.*"
While Not oExec.StdOut.AtEndOfStream
Dim regexMatches
Dim Volume, Drive, Description, Redundancy, RaidStatus
Dim CurrentLine : CurrentLine = oExec.StdOut.ReadLine
Set regexMatches = RegexParse.Execute(CurrentLine)
If (regexMatches.Count > 0) Then
Dim match
Set match = regexMatches(0)
If match.SubMatches.Count >= 8 Then
Volume = match.SubMatches(0)
Drive = match.SubMatches(1)
Description = Trim(match.SubMatches(2))
Redundancy = match.SubMatches(4)
RaidStatus = Trim(match.SubMatches(7))
End If
If RaidStatus <> "Healthy" Then
hasError = 1
'WScript.StdOut.Write "WARNING "
MsgBox "Status of " & Redundancy & " " & Drive & ": (" & Description & ") is """ & RaidStatus & """", 16, "RAID error"
End If
End If
Wend
WScript.Quit(hasError)
Thanks a lot
Option 1 - If the task is running under your user credentials (if not, msgbox will not be visible)
There are two possible sources for the cmd window.
a) The script itself. If the task is executing cscript, the console window will be visible, avoid it calling wscript instead
b) The Shell.exec call. The only way to hide this window is to start the calling script hidden. On start of your script test for the presence of certain argument. If not present, make the script call itself with the argument, using Run method of the WshShell object, and indicating to run the script with hidden window. Second instance of the script will start with the special parameter, so it will run, but this time windows will be hidden.
Option 2 - Running the task under system credentials.
In this case, no window will be visible. All will be running in a separate session. BUT msgbox will not be seen. Change MsgBox call with a call to msg.exe and send a message to current console user.

Locking computer remotely

Is there any way that one can lock a desktop computer remotely? For example, if one accidently leaves a computer logged on, would there be a way to lock that computer using Remote Connection (VPN)?
Use PsExec to invoke:
rundll32.exe user32.dll, LockWorkStation
on your remote PC.
If you are currently on PC_A and want to lock PC_B, type this on your command line (on PC_A):
psexec \\\PC_B -u user -p pass "rundll32.exe user32.dll, LockWorkStation"
This way rundll32.exe user32.dll, LockWorkStation will be invoked on PC_B.
You can create a file with an arbitrary name and the suffix bat use this code in bat file
rundll32.exe user32.dll, LockWorkStation
save and run
You can use SysInternal tools, mainly the PsShutdown tool. You would get an instance of cmd on the PC and execute the lock command.
Example:
psshutdown \\computername -l
Option Explicit
Dim objWMIService, objProcess
Dim strShell, objProgram, strComputer, strExe, strInput
strExe = "rundll32.exe user32.dll,LockWorkStation"
' Input Box to get name of machine to run the process
Do
strComputer = (InputBox(" ComputerName to Run Script",_
"Computer Name"))
If strComputer <> "" Then
strInput = True
End if
Loop until strInput = True
' Connect to WMI
set objWMIService = getobject("winmgmts://"_
& strComputer & "/root/cimv2")
' Obtain the Win32_Process class of object.
Set objProcess = objWMIService.Get("Win32_Process")
Set objProgram = objProcess.Methods_( _
"Create").InParameters.SpawnInstance_
objProgram.CommandLine = strExe
'Execute the program now at the command line.
Set strShell = objWMIService.ExecMethod( _
"Win32_Process", "Create", objProgram)
'WScript.echo "Created: " & strExe & " on " & strComputer
WSCript.Quit
' End of Example of a Process VBScript

VB script to run a Query

I am trying to connect command prompt through VB script and further its connecting with Oracle enviroment to execute some reports of Oracle discoverer.
But the problem is with this VB script only.
line 2: for establishing the connection.
line 7:fetching the current REQUEST_ID.
line 16:XXDIS_EXPORT_CMD_V is a view and cmd is a column.which select a value like this for corresponding REQUEST_ID.
/CONNECT DISCADMIN:"FAI Financials Intelligence"/discbi#deverp /OPENDB "1 Scheduling" /SHEET "Sheet_1" /EXPORT HTML o27673334.out /LOGFILE l27673334.log /BATCH
In the end i want to execute this cmd using VBScript.
Error coming :
"In line 32 tkgoShell was not
recognized"
This is My code:
' Process job
Set objADO =CreateObject("ADODB.Connection")
objADO.Open "Driver={Microsoft ODBC for Oracle}; CONNECTSTRING=deverp; UID=apps; PWD=apps11i;"
MsgBox "Connection Established to Server.", vbExclamation + vbOKOnly, "System"
Do While True
' Check if there is a job to process
Set moRS=objADO.execute("SELECT apps.xxdis_schedule_pkg.start_job REQUEST_ID FROM dual")
moRS.MoveFirst
msRequest = moRS("REQUEST_ID")
'MsgBox msRequest,msRequest
' If no jobs then exit
' If msRequest = "0" Then
Exit Do
' End If
loop
Set moRS=objADO.execute("SELECT cmd EXPORT_CMD FROM apps.xxdis_export_cmd_v " & _
"WHERE request_id = " & msRequest)
MsgBox msRequest,msRequest
moRS.MoveFirst
msExpCmd = moRS("EXPORT_CMD")
' write command into a temporary file
msCmdFile = "r" & msRequest & ".cmd"
dim moOutputStream,filesys,msCommand
Set filesys = CreateObject("Scripting.FileSystemObject")
Set moOutputStream = filesys.CreateTextFile(msCmdFile, True)
' Substitute $SAMBA$ and $TNS$ locally configured variables
moOutputStream.Write Replace(Replace(msCmd, "$SAMBA$", gsOutDir),_
"$TNS$", gsInstance) & vbCRLF
moOutputStream.Close
' Call Discoverer to process the command
msCommand = gsBinDir & gsDiscoExe & " /EUL " & gsEUL & " /CMDFILE " & msCmdFile
Call tkgoShell.Run (msCommand, 1, true)
If I understand your code correctly I can't see anywhere where you're actually creating the tkgoShell.
Try inserting the following 2 rows before your last line:
Dim tkgoShell
Set tkgoShell = WScript.CreateObject ("WScript.Shell")
See here for more information about Shell.Run.

Resources