执行在python bash脚本 [英] Executing a bash script in python

查看:275
本文介绍了执行在python bash脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个expect脚本,当执行,SSH的到服务器并执行一系列命令。伪code是这样的:

I've created an expect script that, when executed, ssh's onto a server and executes a series of commands. Pseudocode looks like this:

#!/usr/bin/expect
spawn ssh usr@myip
expect "password:"
send "mypassword\n";
send "./mycommand1\r"
send "./mycommand2\r"
interact

当从bash shell中(./myscript.txt $)执行code执行罚款。我现在想要做的是有蟒蛇文件中的行运行脚本的命令以同样的方式在bash shell一样。伪code是这样的:

When executed from a bash shell ($ ./myscript.txt) the code executes fine. What I would now like to do is have a line in python file that runs the commands in the script the same way the bash shell does. Pseudocode looks like this:

import subprocess
def runmyscript():
    subprocess.call("myscript.txt", executable="expect", shell=True)
def main():
    run = runmyscript():
if __name__ == '__main__': main()   

我已经放在myscript.txt脚本文件在同一目录作为我的runmyscript.py文件,但是当我运行python的文件我收到错误消息:

I have placed the myscript.txt script file in the same directory as my runmyscript.py file, yet when I run the python file I receive the error:

WindowsError: [Error 2] The system cannot find the file specified

我已经通过在python.org网站的文档阅读,但徒劳无功。有没有人有一个狡猾的解决方案,从的.py code内执行的bash脚本?

I've read through the documentation on the python.org site, but to no avail. Does anyone have a cunning solution for executing bash scripts from within .py code?

解决方案:此code对我的作品

SOLUTION: this code works for me.

child = subprocess.Popen(['bash', '-c', './myscript.txt'], stdout = subprocess.PIPE)

用于此code调用一个期望文件,SSH和从.py文件发送命令到服务器 - 如果你有麻烦内置到您的计算机pycrypto /的paramiko有用的解决方案

Used this code to call an Expect file to ssh and send commands to server from .py file - useful solution if you are having trouble getting pycrypto/paramiko built onto your machine.

推荐答案

下面是一个Python实现你期望的脚本:

Here is a python implementation of your expect script:

import paramiko

user = "user"
pass = "pass"
host = "host"

client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(host, port=22, username=user, password=pass)
client.exec_command("./mycommand1")
client.exec_command("./mycommand2")
client.close()

这篇关于执行在python bash脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆