开发者

Remotely manipulating the execution of a batch file

开发者 https://www.devze.com 2022-12-09 19:06 出处:网络
I have a batch file that is located on one machine that I am invoking remotely from another machine.That batch file is pretty simple; all it does is set some environment variables and then executes an

I have a batch file that is located on one machine that I am invoking remotely from another machine. That batch file is pretty simple; all it does is set some environment variables and then executes an application - the application cr开发者_StackOverflow社区eates a command window and executes inside of it. The application it executes will run forever unless someone types in the command window in which it is executing "quit", at which point it will do some final processing and will exit cleanly. If I just close the command window, the exit is not clean and that is bad for a number of different reasons related to the data that this application produces. Is there a way for me to perhaps write another batch script that will insert the "quit" command into the first command window and then exit?


I'd write a little script using the subprocess module in python, like so:

from subprocess import Popen, PIPE
import os
import os.path
import time

app = Popen(['c:/path/to/app.exe', 'arg1', 'arg2'], stdin=PIPE, env = {
    'YOUR_ENV_VAR_1': 'value1',
    'YOUR_ENV_VAR_2': 'value2',
    # etc as needed to fill environment
    })

while not os.path.exists('c:/temp/quit-app.tmp'):
    time.sleep(60)

app.communicate('quit\n')

print "app return code is %s" % app.returncode

Then, you remotely invoke a batch script that creates c:/temp/quit-app.tmp when you want to shut down, wait a couple of minutes, and then deletes the file.

Naturally, you need Python installed on the Windows machine for this to work.


It sounds like the type of job for which I'd use expect, though I've never used it under Windows.


You could use the < to take the "quit" from a text file instead of the console... but that would quit your process as soon as it loads. Would that work? Otherwise you could write a program to send keystrokes to the console... but I don't think this is a production quality trick.


Do you have access to the actual code of the application? if so you can check for a batch file. Else you can do something like the following using powershell.

    $Process = Get-Process | Where-Object {$_.ProcessName -eq "notepad"}If (!($Process))
{   "Process isn't running, do stuff"
}Else
{   $myshell.AppActivate("notepad")
    $myshell.sendkeys("Exit")
}

I am only suggesting powershell as its easy for you to call the code. you could also put in a loop and wait for it to run.

RE

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号