Open a Putty Window and Run Ssh Commands - Python

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

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.

passing commands to PUTTY

putty.exe does not read from standard input, and does not write to standard output. It is a terminal emulator, so it takes input from the keyboard and writes to its application window.

If you want to pass data through standard input and output descriptors into an ssh connection then use the plink.exe program that comes with the PuTTY package. (It will be in the same directory as putty.exe.) It's not a terminal emulator, it just makes an ssh connection and then drives stdin and stdout, similar to the traditional ssh command on Unix-like systems.

You might even be able to run ssh instead of plink, depending on what Windows release you have and what extra packages you have installed.

Also, I believe both plink and ssh want -i (lower case), not -I (upper case) as the option for specifying a key file.

Conversion of .bat file to open and load putty session into Python

You can use Plink which is a command line application. here more info

import subprocess

sp = subprocess.Popen(['plink', '-ssh', '-l', 'username', '-pw', 'password', 'SessionName'], \
shell = False, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
sp.communicate('lmstat -a\nexit\n'.encode())

OR try with paramiko

import paramiko
import socket


class Point:
def __init__(self,host,username,password,port):
self.host = host
self.username = username
self.password = password
self.port = port

def connect(self):
"""Login to the remote server"""

print("Establishing ssh connection")
self.client = paramiko.SSHClient()
self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# Connect to the server
self.client.connect(hostname=self.host, port=self.port, username=self.username, password=self.password,
timeout=1000, allow_agent=False, look_for_keys=False)
print("Connected to the server", self.host)


Related Topics



Leave a reply



Submit