Python subprocess - running multiple shell commands through SSH

I am trying to open an SSH channel from one Linux block to another, run a few shell commands, and then close SSH.

I have no control over the packages in any field, so something like fabric or paramiko is out of the question.

I was fortunate enough to use the following code to run one bash command, in this case “uptime”, but I'm not sure how to issue one command after another. I expect something like:

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()

What part of the subprocess module do I miss?

thanks

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>
+4
source share
2 answers

, , , , ssh. - : , , , END- . END-, ssh.

from __future__ import print_function,unicode_literals
import subprocess

sshProcess = subprocess.Popen(['ssh', 
                               <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="")

for line in sshProcess.stdout:
    if line == "END\n":
        break
    print(line,end="")
+12

:

for line in sshProcess.stdout:
    if line == "END\n":
        break
    print(line,end="")

for line in sshProcess.stdout:
    if line == "END\n":
        break
    print(line,end="")
-1

All Articles