[英]Python subprocess - run multiple shell commands over SSH
我試圖打開一個從一個 Linux 機器到另一個機器的 SSH 管道,運行一些 shell 命令,然后關閉 SSH。
我無法控制任何一個盒子上的包裹,所以像織物或 paramiko 這樣的東西是不可能的。
我很幸運地使用以下代碼運行了一個 bash 命令,在本例中為“正常運行時間”,但我不確定如何一個接一個地發出一個命令。 我期待類似的東西:
sshProcess = subprocess.call('ssh ' + <remote client>, <subprocess stuff>)
lsProcess = subprocess.call('ls', <subprocess stuff>)
lsProcess.close()
uptimeProcess = subprocess.call('uptime', <subprocess stuff>)
uptimeProcess.close()
sshProcess.close()
我缺少子流程模塊的哪一部分?
謝謝
pingtest = subprocess.call("ping -c 1 %s" % <remote client>,shell=True,stdout=open('/dev/null', 'w'),stderr=subprocess.STDOUT)
if pingtest == 0:
print '%s: is alive' % <remote client>
# Uptime + CPU Load averages
print 'Attempting to get uptime...'
sshProcess = subprocess.Popen('ssh '+<remote client>, shell=True,stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
sshProcess,stderr = sshProcess.communicate()
print sshProcess
uptime = subprocess.Popen('uptime', shell=True,stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
uptimeProcess,stderr = uptimeProcess.communicate()
uptimeProcess.close( )
print 'Uptime : ' + uptimeProcess.split('up ')[1].split(',')[0]
else:
print "%s: did not respond" % <remote client>
基本上,如果您調用 subprocess 它會創建一個本地子進程而不是遠程子進程,因此您應該與 ssh 進程進行交互。 所以沿着這條線:但請注意,如果您動態構建我的目錄,它很容易受到 shell 注入的影響,那么 END 行應該是唯一標識符 為了避免 END 行問題的唯一性,最簡單的方法是使用不同的 ssh 命令
from __future__ import print_function,unicode_literals
import subprocess
sshProcess = subprocess.Popen(['ssh',
'-tt'
<remote client>],
stdin=subprocess.PIPE,
stdout = subprocess.PIPE,
universal_newlines=True,
bufsize=0)
sshProcess.stdin.write("ls .\n")
sshProcess.stdin.write("echo END\n")
sshProcess.stdin.write("uptime\n")
sshProcess.stdin.write("logout\n")
sshProcess.stdin.close()
for line in sshProcess.stdout:
if line == "END\n":
break
print(line,end="")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.