首页 \ 问答 \ 使用Python子进程和字符串格式化(Using Python subprocess and string formating)

使用Python子进程和字符串格式化(Using Python subprocess and string formating)

我试图使用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>'])

I am attempting to call a windows command with relevant arguments using python's subprocess . The command is executing and the arguments and their values look to be correct, however It only seems to be working correctly when using the "local mode" -l. I'm getting an invalid argument/option error when using the remote mode. Could any point out where im going wrong?

Could anyone point out how to format the subprocess.check_ouput() arguments correctly to include the variables given at commandline when executing the script? As you can see ive tryd using string formating, both old and new to try get it working as I cant workout how to add the last domain variable inbetween the filter (/FI) argument value without string formatting.

expected commandline to execute

tasklist /V /S 192.168.1.122 /U 'DOMAIN'\'USERNAME' /P 'PASSWORD' /FI "USERNAME eq 'DOMAIN'\*"

with this commandline example of the script:

hunter.py -d DOMAIN -u USERNAME -p PASSWORD -s servers.txt

This is the error:

ERROR: Invalid argument/option - '/S 192.168.1.122'.
Type "TASKLIST /?" for usage.

Clearly the argument is correct "visually" correct anyway, here is the usage for the tasklist:

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.

This is the python code i have so far;

#!/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>'])

原文:https://stackoverflow.com/questions/22582168
更新时间:2022-03-03 09:03

最满意答案

我已经解决了这个问题。 实际上我没有意识到但问题是固定的。 问题解决后我做了Windows更新:)下面显示的更新可能有助于其他程序员。

在此处输入图像描述


I have solved this problem. Actually I did not consciously but probleb was fixed. I did Windows Updates after problem solved :) Updates shown below might be help another programmers.

enter image description here

相关问答

更多

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)