简体   繁体   English

如何从Python脚本运行多个外部命令

[英]How to run Multiple external commands from Python Script

I have a requirement where I have to run these few commands in the terminal using a python script.The requirement is as such: 我有一个要求,我必须在终端中使用python脚本运行这几个命令。

ssh abc.xyz.com ssh abc.xyz.com

After ssh to that machine, ssh to the environment SSH到那台机器之后,SSH到环境

ssh qa SSH QA

and then run few commands in the environment 然后在环境中运行一些命令

I have tried achieving this using os.system() and using subprocess.call() but no luck. 我尝试使用os.system()和subprocess.call()实现这一点,但是没有运气。

Specifically, I tried doing this : 具体来说,我尝试这样做:

import subprocess
from time import sleep
subprocess.call("ssh abc.def.com", shell=True)
subprocess.call("python", shell=True)
sleep(0.3)
subprocess.call("ssh qa", shell=True)

i am not sure about your approach of connecting to remote server and executing command there with subprocess. 我不确定您连接到远程服务器并通过子进程在那里执行命令的方法。

Instead You can use paramiko module to connect with remote server and execute command 相反,您可以使用paramiko模块与远程服务器连接并执行命令

import paramiko 
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('192.168.1.26',port=22,username='root',password='default')

# you can use your own commands in exec_command()

stdin,stdout,stderr=ssh.exec_command('echo 123')
output=stdout.readlines()
print '\n'.join(output)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM