【问题标题】:Using Python subprocess and string formating使用 Python 子进程和字符串格式化
【发布时间】:2014-03-22 19:05:38
【问题描述】:

我正在尝试使用 python 的 subprocess 调用带有相关参数的 windows 命令。该命令正在执行并且参数及其值看起来是正确的,但是它似乎只有在使用“本地模式”-l 时才能正常工作。 使用远程模式时出现invalid argument/option 错误。谁能指出我哪里出错了?

谁能指出如何正确格式化subprocess.check_ouput() 参数以包含在执行脚本时在命令行中给出的变量?正如您所看到的,我尝试使用字符串格式化,无论是旧的还是新的,都试图让它工作,因为我无法训练如何在没有字符串格式化的过滤器(/FI)参数值之间添加最后一个domain 变量。

预期要执行的命令行

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>'])

【问题讨论】:

    标签: python windows command-line


    【解决方案1】:

    将您的参数作为列表中的单独元素传递,并将字符串格式应用于最后一个元素,而不是 subprocess.check_output() 调用的输出:

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

    请注意,我还删除了最后一个参数中的 ' 引用,将其留给 subprocess 模块。

    这也假设domain 始终是一个非空字符串;如果不是这种情况,请使用:

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

    例如只有在实际指定了domain 时才使用\ 反斜杠。

    【讨论】:

    • arr 您将格式保留在括号内。谢谢Martijin Pieters。我现在应用更改并回复您。
    • 再次感谢 Martijin 解释如何格式化参数。尝试执行 tasklist 命令时为什么会出现上述错误的任何线索?
    • @user3449832:我已经向您展示了/Sserverl 应该是参数列表中的单独元素;你也改正了吗?
    • 是的,我和你在上面做的一样。发布新更改的代码对我来说是一种好习惯吗?替换旧的?
    • 仍然显示相同的消息?
    猜你喜欢
    • 2021-12-06
    • 1970-01-01
    • 2012-06-27
    • 2012-07-25
    • 1970-01-01
    • 1970-01-01
    • 2019-11-28
    • 2011-07-28
    • 1970-01-01
    相关资源
    最近更新 更多