'Automated interaction within ssh session
I need to collect some output via ssh from different devices but there are two caveats:
- The devices are interactively asking for credentials so login can't be easily automated
- The output is paged, so it is required to press "Enter" a number of times to get to the end of it
I've tried using paramiko_expect, I can manage the authentication but then I can't figure out how to loop in a while-like style.
from paramiko_expect import SSHClientInteraction
try:
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(addresses[0], username = username, password = password, look_for_keys = False, allow_agent = False)
output = ""
with SSHClientInteraction(client, timeout = 10, display = False) as interact:
interact.expect(['User:.*'])
interact.send(username)
interact.expect(['Password:.*'])
interact.send(password)
interact.expect(['.*>'])
interact.send('get output')
interact.expect(['.*>','.*More or (q)uit.*'])
keepOnLooping = True
while keepOnLooping == True:
if interact.last_match == '.*More or (q)uit.*':
interact.send(interact.send(' '))
interact.expect(['.*>','.*More or (q)uit.*'])
keepOnLooping = True
elif interact.last_match == '.*>':
interact.send(interact.send(' '))
keepOnLooping = False
output = interact.current_output
I've tried with pexpect (pxssh) but I'm failing at the authentication phase.
from pexpect import pxssh
import getpass
try:
s = pxssh.pxssh()
hostname = input('hostname: ')
username = input('username: ')
password = getpass.getpass('password: ')
s.login(hostname, username, password)
s.expect('User:.*')
s.sendline(username)
s.expect('Password:.*')
s.sendline(password)
Any suggestions on how to automate the mentioned proceedures?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
