'Python paramiko get the terminal prompt
Is it possible to get the terminal prompt of a remote host via paramiko? This is the only thing I've found that works but its crazy b/c I need to have a sleep b/c it might return before the host sends the prompt.
import time
def get_prompt(host):
with paramiko.SSHClient() as ssh:
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, 22, 'random_user', 'random_password', timeout=1)
channel = ssh.invoke_shell()
time.sleep(5)
prompt = channel.recv(1000).decode()
return prompt
Solution 1:[1]
hope I am not too late on this, I had the same problem, my solution was flushing the paramiko buffer before getting the prompt, and sending \n
buffer_size = # buffer size number
def flush(connection):
while connection.recv_ready():
connection.recv(buffer_size)
def get_prompt(connection):
flush(connection) # flush everything from before
connection.sendall('\n')
time.sleep(.3)
data = str(connection.recv(buffer_size), encoding='utf-8').strip()
flush() # flush everything after (just in case)
return data
def create_client(host):
with paramiko.SSHClient() as ssh:
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, 22, 'random_user', 'random_password', timeout=20)
connection = ssh.invoke_shell()
time.sleep(2) # wait for banners
prompt = get_prompt(connection)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | dsal3389 |