用于执行外部命令的Python脚本

时间:2015-08-31 16:09:38

标签: python automation remote-access

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

e.g。

  1. ./ MY-
  2. print_output_1 [with in my_program ]
  3. print_output_2 [with in my_program ]
  4. 退出[在 my_program ]
  5. 如果我手动运行命令终端将得到这样的东西

    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$
    

    所以我应该得到" first_line_printed_with_unknown_length"和" second_line_printed_with_unknown_length"在像

    这样的python字符串中
    execute(my_program)
    str1 = execute( print_output_1 )
    str2 = execute( print_output_2 )
    val = execute( exit )
    

2 个答案:

答案 0 :(得分: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可能存在安全隐患。看警告   在常用参数下获取详细信息。

答案 1 :(得分:0)

可以使用ssh(即ssh命令)和ssh,就像任何shell-executable命令都可以用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实现,但如果你不需要交互性,那可能会有点过分。