【问题标题】:Python script to execute external commands执行外部命令的 Python 脚本
【发布时间】:2015-08-31 16:09:38
【问题描述】:

我需要向当前正在执行的程序发出一些命令,并将当前(远程)执行程序的输出转换为脚本中的某个字符串。我目前遇到的问题是我不知道每个命令的输出,因为它可以从用户那里读取,所以输出也会有所不同。

例如

  1. ./my_program
  2. print_output_1 [在 my_program 中]
  3. print_output_2 [在 my_program 中]
  4. exit [with in my_program]

如果我手动运行命令,终端会得到这样的结果

bash$ ./my_programe
my_program: print_output_1
my_program:first_line_printed_with_unknown_length
my_program: print_output_2
my_program:second_line_printed_with_unknown_length
my_program: exit
bash$

所以我应该在 python 字符串中得到“first_line_printed_with_unknown_length”和“second_line_printed_with_unknown_length”

execute(my_program)
str1 = execute( print_output_1 )
str2 = execute( print_output_2 )
val = execute( exit )

【问题讨论】:

  • 您尝试过什么了吗?如果没有,你应该。如果有,结果如何? ..但是是的,你可以使用Python
  • 感谢您的回复。请告诉我可以查看的任何包名称。
  • 我已经为你添加了答案。它应该让你对如何解决这个问题有一个非常基本的想法。

标签: python automation remote-access


【解决方案1】:

您可以使用subprocess 模块来执行外部命令。最好先从更简单的命令开始,以了解所有要点。下面是一个虚拟示例:

import subprocess
from subprocess import PIPE

def main():
    process = subprocess.Popen('echo %USERNAME%', stdout=PIPE, shell=True)
    username = process.communicate()[0]
    print username #prints the username of the account you're logged in as

if __name__ == '__main__':
    main()

这将从echo %USERNAME% 获取输出并存储它。很简单,只是为了给你一个大致的想法。

来自上述文档:

警告:使用 shell=True 可能存在安全隐患。见警告 在常用参数下了解详细信息。

【讨论】:

    【解决方案2】:

    可以使用 ssh(即ssh 命令)和 ssh,就像任何 shell 可执行命令都可以包装在 Python 中一样,所以答案是肯定的。像这样的东西可以工作(虽然我没有尝试):

    import subprocess
    
    remote_command = ['ls', '-l']
    ssh_command = ['ssh', 'user@hostname.com'] + remote_command
    proc = subprocess.Popen(ssh_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    stdout, stderr = proc.communicate()
    
    # stdout now contains the output of the remote command
    # stderr now contains the error stream from the remote command or from ssh
    

    您也可以使用 Paramiko,它是 Python 中的 ssh 实现,但如果您不需要交互性,这可能是矫枉过正。

    【讨论】:

      猜你喜欢
      • 2013-07-01
      • 2019-09-17
      • 2020-04-15
      • 1970-01-01
      • 1970-01-01
      • 2013-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多