Python subprocess Popen 运行多个命令

0 投票
1 回答
984 浏览
提问于 2025-04-17 19:51

我想在Python中一次性执行多个命令。我在Windows上安装了putty。

  1. 先通过ssh连接到Linux机器

    ssh_command_string: plink -i yourppk.ppk ec2-user@instanceIp
    
  2. 在那台机器上执行一个命令,这个命令会生成一个文件

    export_project_command_string: ./AppManage -export -out /opt/notme-Facebook.xml -app "Silver Fabric/notme-FacebookPostsExtraction0118" -user username-pw password -domain ion
    
  3. 下载这个文件

    download_command_string: pscp -scp -i yourppk.ppk ec2-user@instanceIp:/opt/notme-Facebook.xml d:\
    

这些命令我逐个测试都没问题,但我不知道怎么在Python中一次性执行它们。

我试过以下代码,但没有成功:

LINE_BUFFERED = 1
    #NOTE: the first argument is a list
    p = Popen(['cat'], shell = True, bufsize=LINE_BUFFERED, stdin=PIPE, stdout = PIPE, stderr = PIPE)
    for cmd in [ssh_command_string, cd_command_string, export_project_command_string, download_command_string]:
        time.sleep(1) # a delay to see that the commands appear one by one
        p.stdin.write(cmd)
        p.stdin.flush()
    # even without .flush() it works as expected on my machine
    p.stdin.close()

1 个回答

0

可以看看fabric,它可以帮助你在服务器上执行一些重复的或自动化的任务。

撰写回答