-1

would like to open an ssh session, run commands and get the output real-time as the process runs (this base will involve running additional commands on the remote server)

from subprocess import Popen, PIPE

with Popen(['ssh <server-domain-name>',
            ],shell=True,
           stdin=PIPE, stdout=PIPE, stderr=PIPE,
           universal_newlines=True) as ssh:
    output1 = ssh.stdin.write('ls -l')
    output2 = ssh.stdin.write('mkdir test')
    status = ssh.poll()

print(output1)
print(output2)

so far this is what I have, using ssh.communicate[<command>] gives the right output but closes the subproceess after the first command, any thoughts?

SimonSK
  • 153
  • 4
  • 12
  • Are you sure stdin should be a pipe? – John Gordon Aug 09 '20 at 14:22
  • Using `shell=True` here is wrong, but happens to work on Windows. You really want to avoid `shell=True` whenever you can, though. See [Actual meaning of `shell=True` in `subprocess`](https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess); in this case, try `Popen('ssh', server], ...)` but as you discovered, you really want a higher-level library like Paramiko or Expect for talking to an interactive process on a remote server. – tripleee Aug 09 '20 at 14:23

1 Answers1

0

worked for me

from fabric2 import Connection
with Connection('<host>') as c:
    print(CGREEN +'connected succsfully!' + CEND)

    #gather user info
    user = io.StringIO
    user = c.run("whoami", hide=True)
    print(f'user found:{user.stdout} ')

    #fetching files
    c.run(<command>, pty=True)
SimonSK
  • 153
  • 4
  • 12