Python Forum
Reading text from Putty window
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Reading text from Putty window
#1
Hi all,

Im new to Python (3.7)

I'm Trying to automate Putty for SSH/Telnet/Serial connection
it more comfortable to do it through Putty because the connection type changes.

i want it to read the output from putty, so if it asks for "username" it will "answer" correctly.

this is my script:

from pywinauto.application import Application
from pynput.keyboard import Key, Controller

print('Configuring')

app = Application().start(cmd_line=u'"C:\\...putty.exe" ')
puttyconfigbox = app.PuTTYConfigBox
puttyconfigbox.wait('ready')
listbox = puttyconfigbox.ListBox
listbox.select(u'COM5')
button = puttyconfigbox[u'&Load']
button.click()
button2 = puttyconfigbox[u'&Open']
button2.click()

keyboard = Controller()
keyboard.press(Key.enter)

keyboard.type('batm')
keyboard.press(Key.enter)
keyboard.type('enable\nconf t\n')
how can i do it?

Thanks in advance

[Image: E1qvXTm.png]
Reply
#2
There are many ways to get ssh connection via console in Windows. Eventually you can use bash in sygwin or WSL. It seems you chose the most difficult way to automate your routine.
Reply
#3
I didn't succeed in other way.. telnetlib and such didn't react with the device. anyone has an idea how to read from a terminal window?
Reply
#4
Have you considered using Expect for this, rather than building your own thing?
Reply
#5
I guess you want to automate tasks.

You should use Libraries, which gives you direct access to SSH.
Putty is not the solution for it. I made a little example with Paramiko.
This library works on Windows and *nix.

import sys
import getpass
from pathlib import Path
from argparse import ArgumentParser
from paramiko.client import (
    SSHClient,
    MissingHostKeyPolicy,
)
from paramiko.ssh_exception import AuthenticationException


def ask_password():
    return getpass.getpass('Please enter password: ')


def connect(
    hostname,
    username=None,
    password=None,
    port=22,
    key=False,
    **kwargs,
    ):    
    client = SSHClient()
    client.set_missing_host_key_policy(MissingHostKeyPolicy)
    if key:
        # use only private keys for login,
        # if it was explicit requested
        client.load_system_host_keys()
    client.connect(hostname, port=port, username=username, password=password)
    return client


def command_executor(client, script):
    with script.open() as fd:
        for line in fd:
            print(f'Executing command: {line.rstrip()}')
            stdin, stdout, stderr = client.exec_command(line)
            stdout, stderr = stdout.read().decode(), stderr.read().decode()
            print(stdout, end='')


def main(**kwargs):
    if not kwargs['key']:
        kwargs['password'] = ask_password()
    client = connect(**kwargs)
    command_executor(client, kwargs['script'])
    client.close()


if __name__ == '__main__':
    parser = ArgumentParser()
    parser.add_argument('hostname', help='Hostname of the host you want to connect')
    parser.add_argument('username', type=str, help='User for login')
    parser.add_argument('script', type=Path, help='Path to script file, which should executed')
    parser.add_argument('--port', type=int, default=22, help='Port of SSH service')
    parser.add_argument('--key', action='store_true', help='Use only private key for login') 
    args = parser.parse_args()
    if not args.script.exists():
        print(f'The script {args.script} does not exist')
        sys.exit(1)
    try:
        main(**vars(args))
    except AuthenticationException:
        print('Problem with authentication', file=sys.stderr)
        sys.exit(2)
Hint: Storing passwords in source code is not a good idea.
If you want to store your password, then do it in a file and
read the file in the script to get the password.

Better is, if you crate a public/private key pair and put
the public key in .ssh/authorized_hosts
You should protect the private key with a passphrase and
the passphrase can be stored in a file.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#6
Can we use Paramiko for Telnet Connection also?
If not then how can we achieve this?
I tried through Telnet lib but it gives error after connection and is not able to read from the main screen in putty.

Error:
" Unable to use your terminal.Check your PROTERMCAP'file(443)Could not find terminal type
unknown"
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Is there a way to call and focus any popup window outside of the main window app? Valjean 6 1,608 Oct-02-2023, 04:11 PM
Last Post: deanhystad
  Start Putty into Python Form Schlazen 5 5,331 Dec-13-2022, 06:28 AM
Last Post: divya130
  Pyspark Window: perform sum over a window with specific conditions Shena76 0 1,131 Jun-13-2022, 08:59 AM
Last Post: Shena76
  Reading Multiple text Files in pyhton Fatim 1 1,885 Jun-25-2021, 01:37 PM
Last Post: deanhystad
  reading text file with gtts Nickd12 0 1,801 Oct-22-2020, 09:37 PM
Last Post: Nickd12
  How to update libc6 with Putty SSH? drogontargaryen 1 1,894 Jul-20-2019, 03:35 PM
Last Post: ndc85430
  Issue in reading a text file contains dict data bharathappriyan 4 3,178 Sep-27-2018, 01:45 PM
Last Post: Larz60+
  Reading and writing to text file has format change cheerful 3 3,672 Dec-21-2017, 07:53 AM
Last Post: Larz60+
  reading and writing to a text file help jobemorgan 4 3,724 Sep-12-2017, 12:09 PM
Last Post: Sagar

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020