Search code examples
pythonpython-3.xsshsubprocessputty

Open a PuTTY window via Python subprocess.Popen (or Paramiko session) and run number of shell commands (like "top") in the same window


I want to open a PuTTY window, login to some server and enter few commands right after that and at the end save the output. I want to see the PuTTY window open and all activity that I am doing via program (hence need PuTTY GUI).

Here is what I have tried: I am able to open a new window and login in it. But using stdin.write I am not able to enter further commands in the same window. What am I doing wrong here? I am very new to python. Please help.

import subprocess
from subprocess import Popen, PIPE, STDOUT

p = subprocess.Popen("putty.exe demo@Test.Rebex.Net -pw password", stdout=PIPE, stdin=PIPE, stderr=STDOUT)
p.stdin.write("ls".encode("utf-8"))
print(p.stdout.readlines())

I have tried Paramiko, and don't want to use it, as it fails to display/print the output of commands like top.


Solution

  • PuTTY is a GUI application, it does not use a standard input. It is not intended for automation. For automation, you can use Plink, what is a console equivalent of PuTTY.
    See also Pipe PuTTY console to Python script


    Though you should use Paramiko. It does not fail to display/print the output of commands like "top". It' not what it is for. You have to attach it to a terminal to achieve what you want. See Running interactive commands in Paramiko.

    Or for automation, you better run the top non-interactively. See your other question Collect output from top command using Paramiko in Python.