0

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

My current code:

 import subprocess
 import sys

 HOST="[email protected]"
 # 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

2

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.