使用Python子流程和字符串格式化

使用Python子流程和字符串格式化,python,windows,command-line,Python,Windows,Command Line,我正试图使用python的子进程调用带有相关参数的windows命令。命令正在执行,参数及其值看起来是正确的,但它似乎只有在使用“本地模式”-l时才能正常工作。 使用远程模式时,我收到一个无效参数/选项错误。有人能指出我哪里出了问题吗 是否有人能指出如何格式化子流程。请正确检查\u output()参数,以包括执行脚本时命令行中给定的变量?正如您所看到的,我尝试使用字符串格式,无论是旧的还是新的,尝试让它工作,因为我无法解决如何在没有字符串格式的情况下在筛选器(/FI)参数值之间添加最后一个域变

我正试图使用python的
子进程
调用带有相关参数的windows命令。命令正在执行,参数及其值看起来是正确的,但它似乎只有在使用“本地模式”
-l
时才能正常工作。 使用远程模式时,我收到一个
无效参数/选项
错误。有人能指出我哪里出了问题吗

是否有人能指出如何格式化
子流程。请正确检查\u output()
参数,以包括执行脚本时命令行中给定的变量?正如您所看到的,我尝试使用字符串格式,无论是旧的还是新的,尝试让它工作,因为我无法解决如何在没有字符串格式的情况下在筛选器(/FI)参数值之间添加最后一个
变量

预期要执行的命令行

tasklist /V /S 192.168.1.122 /U 'DOMAIN'\'USERNAME' /P 'PASSWORD' /FI "USERNAME eq 'DOMAIN'\*"
使用此脚本的命令行示例:

hunter.py -d DOMAIN -u USERNAME -p PASSWORD -s servers.txt
这是错误:

ERROR: Invalid argument/option - '/S 192.168.1.122'.
Type "TASKLIST /?" for usage.
显然,该参数是正确的,不管怎样,“视觉上”都是正确的,下面是任务列表的用法:

Description:
This tool displays a list of currently running processes on
either a local or remote machine.

Parameter List:
/S     system           Specifies the remote system to connect to.

/U     [domain\]user    Specifies the user context under which
                       the command should execute.

/P     [password]       Specifies the password for the given
                       user context. Prompts for input if omitted.

/M     [module]         Lists all tasks currently using the given
                        exe/dll name. If the module name is not
                        specified all loaded modules are displayed.

/SVC                    Displays services hosted in each process.

/APPS                   Displays Store Apps and their accociated processes.

/V                      Displays verbose task information.

/FI    filter           Displays a set of tasks that match a
                        given criteria specified by the filter.

/FO    format           Specifies the output format.
                        Valid values: "TABLE", "LIST", "CSV".

/NH                     Specifies that the "Column Header" should
                        not be displayed in the output.
                        Valid only for "TABLE" and "CSV" formats.
/?                      Displays this help message.
这是迄今为止我所掌握的python代码

#!/usr/bin/python

"""
Description:

Used for checking users logged into a list of servers.

Usage:
  hunter.py [-u <username>] [-p <password>] [-s <FILE>] (-d <domain>)
  hunter.py (-d <domain>) (-l)
  hunter.py -h | --help
  hunter.py --version

Options:
  -l --local
  -u --username
  -h --help     Show this screen.
  --version     Show version.
  -p --password
  -d --domain
  -s --serverfile=FILE
  """
from docopt import docopt
import subprocess
from subprocess import CalledProcessError

def tldomain(serverlist, domain, username, password):
    nlist = serverlist
    for serverl in nlist:
        try:
            print subprocess.check_output(["tasklist", "/V", "/S " + serverl, "/U" + domain, "\\" + username, "/P" + password, "/FI", "'USERNAME eq %s\\\*'"]) % domain
        except CalledProcessError as e:
            print(e.returncode)

def tllocal(domain):
        try:
            cmd = 'tasklist /V /FI "USERNAME eq {0}\\*"' .format(domain)
            subprocess.call(cmd)
        except OSError as e:
            print e

def getservers(servers):
        slist = open(servers).readlines()
        return [s.replace('\n', '') for s in slist]

if __name__ == "__main__":
    arguments = docopt(__doc__, version='0.1a')
    print arguments

    if (arguments['--local']) == False:
        serverlist = getservers(arguments['--serverfile'])
        tldomain(serverlist, arguments['<domain>'], arguments['<username>'], arguments['<password>'])

    else:
        tllocal(arguments['<domain>'])
#/usr/bin/python
"""
说明:
用于检查登录到服务器列表的用户。
用法:
hunter.py[-u][-p][-s](-d)
hunter.py(-d)(-l)
hunter.py-h |--救命
hunter.py--版本
选项:
-l--本地
-u--用户名
-h--帮助显示此屏幕。
--版本显示版本。
-p--密码
-d——域
-s--serverfile=FILE
"""
从docopt导入docopt
导入子流程
从子流程导入调用的流程错误
def tldomain(服务器列表、域、用户名、密码):
nlist=serverlist
对于nlist中的serverl:
尝试:
打印子流程。检查\U输出([“任务列表”、“/V”、“/S”+服务器L、/U”+域、\\“+用户名、/P”+密码、/FI”、“'username eq%S\\\\*”])%domain
除被调用的进程错误为e外:
打印(如返回代码)
def tllocal(域):
尝试:
cmd='tasklist/V/FI“USERNAME eq{0}\\\*”。格式(域)
子进程调用(cmd)
除O错误为e外:
打印e
def getservers(服务器):
slist=open(服务器).readlines()
返回[s.replace('\n','')用于slist中的s]
如果名称=“\uuuuu main\uuuuuuuu”:
arguments=docopt(uuu doc_uuuuu,version='0.1a')
打印参数
如果(参数['--local'])==False:
serverlist=getservers(参数['--serverfile'])
tldomain(服务器列表,参数[''],参数['],参数[''])
其他:
tllocal(参数[“”])

将参数作为列表中的单独元素传递,并将字符串格式应用于最后一个元素,而不是子流程的输出。检查\u output()
调用:

print subprocess.check_output(
    ["tasklist", "/V", "/S", serverl, "/U", domain + "\\" + username,
     "/P", password, "/FI", "USERNAME eq %s\\*" % domain]) 
请注意,我还从最后一个参数中删除了
引号,将其留给
子流程
模块

这还假设
始终是非空字符串;如果情况并非如此,请使用:

if domain:
    domain += '\\'

print subprocess.check_output(
    ["tasklist", "/V", "/S", serverl, "/U", domain + username,
     "/P", password, "/FI", "USERNAME eq %s*" % domain]) 

e、 g.仅当实际指定了
时才使用
\
反斜杠。

arr将格式保留在括号内。谢谢Martijin Pieters。我现在应用更改,然后回复您。再次感谢Martijin解释如何设置参数的格式。关于我在执行tasklist命令时出现上述错误的原因,有什么线索吗?@user3449832:我已经向您展示了
/S
serverl
应该是参数列表中的独立元素;你也纠正了吗?是的,我也纠正了,就像你刚才所做的那样。对我来说,发布新修改的代码是一种好的做法吗?更换旧的?并且仍然显示相同的消息?