Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

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 [email protected] -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.

question from:https://stackoverflow.com/questions/65916302/open-a-putty-window-via-python-subprocess-popen-or-paramiko-session-and-run-nu

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...