Как можно получить stdout команды в реальном времени через Paramiko?
Необходимо выполнить команду, подключившись по SSH(я использую Paramiko), и получить от неё строку stdout тогда, когда она была возвращена.
Сначала я пытался сделать это через асинхронную функцию, но до конца не понял, как это нужно делать.
Текущий код запускается, но не даёт stdout команды вообще, хотя он есть.
Можно ли как-то получить stdout команды в реальном времени через Paramiko или любой другую SSH библиотеку в питоне?
Модуль paramiko#
Paramiko — это реализация протокола SSHv2 на Python. Paramiko предоставляет функциональность клиента и сервера. В книге рассматривается только функциональность клиента.
Так как Paramiko не входит в стандартную библиотеку модулей Python, его нужно установить:
Подключение выполняется таким образом: сначала создается клиент и выполняются настройки клиента, затем выполняется подключение и получение интерактивной сессии:
SSHClient это класс, который представляет соединение к SSH-серверу. Он выполняет аутентификацию клиента. Следующая настройка set_missing_host_key_policy не является обязательной, она указывает какую политику использовать, когда выполнятся подключение к серверу, ключ которого неизвестен. Политика paramiko.AutoAddPolicy() автоматически добавляет новое имя хоста и ключ в локальный объект HostKeys.
Метод connect выполняет подключение к SSH-серверу и аутентифицирует подключение. Параметры:
look_for_keys — по умолчанию paramiko выполняет аутентификацию по ключам. Чтобы отключить это, надо поставить флаг в False
allow_agent — paramiko может подключаться к локальному SSH агенту ОС. Это нужно при работе с ключами, а так как в данном случае аутентификация выполняется по логину/паролю, это нужно отключить.
После выполнения предыдущей команды уже есть подключение к серверу. Метод invoke_shell позволяет установить интерактивную сессию SSH с сервером.
Метод send#
Метод send — отправляет указанную строку в сессию и возвращает количество отправленных байт или ноль если сессия закрыта и не удалось отправить команду:
В коде после send надо будет ставить time.sleep, особенно между send и recv. Так как это интерактивная сессия и команды набираются медленно, все работает и без пауз.
Метод recv#
Метод recv получает данные из сессии. В скобках указывается максимальное значение в байтах, которое нужно получить. Этот метод возвращает считанную строку.
Paramiko: read from standard output of remotely executed command
so I was working with paramiko for some basic SSH testing and I’m not getting any output into stdout. Heres my code.
So whenever I run this, the command is executed (as seen by if I do something like a cp, the file is copied), but I always get «There was no output for this command». When stdout=stdout.readlines() is printed, [] is the output. In addition, if I add a print statement into the for loop, it never gets run. Could someone help me out here? Thanks!
5 Answers 5
You have closed the connection before reading lines:
![]()
The code in the accepted answer may hang, if the command produces also an error output. See Paramiko ssh die/hang with big output.
An easy solution, if you do not mind merging stdout and stderr , is to combine them into one stream using Channel.set_combine_stderr :
*Interactive example : ====Part 1, this show the sh output in server ,at the end of is «>» need some input to continual or exit ======
Как через paramiko получить значение консоли
I am executing a long-running python script via ssh on a remote machine using paramiko. Works like a charm, no problems so far.
Unfortunately, the stdout (respectively the stderr ) are only displayed after the script has finished! However, due to the execution time, I’d much prefer to output each new line as it is printed, not afterwards.
How can this be achieved? Note: Of course one could pipe the output to a file and ‘less’ this file via another ssh session, but this is very ugly and I need a cleaner, ideally pythonic solution 🙂
How to Execute Shell Commands in a Remote Machine using Python – Paramiko
Paramiko is a Python library that makes a connection with a remote device through SSh. Paramiko is using SSH2 as a replacement for SSL to make a secure connection between two devices. It also supports the SFTP client and server model.
Authenticating SSH connection
To authenticate an SSH connection, we need to set up a private RSA SSH key (not to be confused with OpenSSH). We can generate a key using the following command:
This will prompt us to provide a name for our key. Name it whatever you like and generate a public/private RSA key pair. Enter the name by which you wish to save the key.
Next, you’ll be prompted to provide a password (feel free to leave this blank).
Now that we have our key, we need to copy this to our remote host. The easiest way to do this is by using ssh-copy-id:
If you’d like to check which keys you already have, these can be found in your system’s .ssh directory:
We’re looking for keys that begin with the following header:
SSH(Secure Shell) is an access credential that is used in the SSH Protocol. In other words, it is a cryptographic network protocol that is used for transferring encrypted data over the network. It allows you to connect to a server, or multiple servers, without having you remember or enter your password for each system that is to log in remotely from one system into another.
Installing Paramiko
To install paramiko library, run the subsequent command in the command prompt. paramiko needs cryptography as a dependency module. So run both commands in the command prompt :
pip install paramiko
pip install cryptography
After installation is completed, now we’ll hook up with a remote SSH server using paramiko library. Code snippet for an equivalent is given below: