0

I am using subprocess to connect ssh session to remote host to execute multiple commands.

My current code:

 import subprocess
 import sys

 HOST="admin@10.193.180.133"
 # Ports are handled in ~/.ssh/config since we use OpenSSH
 COMMAND1="network port show"
 ssh = subprocess.Popen(["ssh", "%s" % HOST, COMMAND1],
                   shell=False,
                   stdout=subprocess.PIPE,
                   stderr=subprocess.PIPE)
 result = ssh.stdout.readlines()
 if result == []:
     error = ssh.stderr.readlines()
     print >>sys.stderr, "ERROR: %s" % error
 else:
      resp=''.join(result)
      print(resp)
COMMAND2="network interface show"

 ssh = subprocess.Popen(["ssh", "%s" % HOST, COMMAND2],
                   shell=False,
                   stdout=subprocess.PIPE,
                   stderr=subprocess.PIPE)
 result = ssh.stdout.readlines()
 if result == []:
     error = ssh.stderr.readlines()
     print >>sys.stderr, "ERROR: %s" % error
 else:
     resp=''.join(result)
     print(resp)

In above case my code asking me to enter password twice.

But what i want make is the password should be ask one time and multiple commands has to be execute.

Please help

asteroid4u
  • 79
  • 2
  • 9
  • Possible duplicate of [Python subprocess - run multiple shell commands over SSH](http://stackoverflow.com/questions/19900754/python-subprocess-run-multiple-shell-commands-over-ssh) – Serge Ballesta Apr 03 '17 at 12:06
  • https://stackoverflow.com/a/66620427/3701072 here is my take on a running multiple commands. – Hades Mar 14 '21 at 02:09

1 Answers1

2

You are opening two connections in your code, so it's natural that you'll have to enter a password twice.

Instead, you can open one connection and pass multiple remote commands.

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("echo END\n")
sshProcess.stdin.close()

see here for more details

Community
  • 1
  • 1
philshem
  • 24,761
  • 8
  • 61
  • 127