I am doing ssh using the subprocess run command. I am aware of popen
through https://www.cyberciti.biz/faq/python-run-external-command-and-get-output/ - it works.
I am trying run command at the moment. I am getting an error when I use the run command: Pseudo-terminal will not be allocated because stdin is not a terminal
.
>>> import subprocess
>>> cmd = ["ssh", "-i", "sshkey.pem", "user@111.1.1.1"]
>>> ip = 'exit'.encode('utf-8')
>>> result = subprocess.run(cmd, stdout=subprocess.PIPE, input=ip)
>>> # I want to access the ssh terminal here and run a few commands like ip in the ssh terminal
My basic goal is to:
Run a few commands like
exit
(theip
variable) in the SSH terminal using code. Which arguments can be used for SSH terminal input and output in the SSH pseudo terminal,IF
I can access one in.run()
command. (I am looking at this Running shell command and capturing the output)Run a few commands like exit in the SSH terminal using shell with (a.) possibly be able to stream output of the SSH terminal and (b.) possibly be able to stream inputs into the SSH terminal.
UPDATE:
Able to get into the shell using the .popen()
function. Unable to run list of commands from code automatically even using .communicate()
function even with .popen()
using input
argument, not just .run()
function.
cmd = ["ssh", "-i", "sshkey.pem", "user@111.1.1.1"]
r = subprocess.run(cmd, stdout=subprocess.PIPE, input=ip)
# does not work with ip
# Unable to run list of commands into the process automatically via commands
c = subprocess.call(cmd, shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
# Unable to run list of commands into the process automatically via commands
p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output = p.communicate(input='exit'.encode())[0]
# Able to get into the shell of the subprocess
# but unable to run list of commands into the shell automatically, output doesnot work using `input` options