Issue
I tried to read the docker container logs using an ssh connection.
def test_read_ssh():
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(IPAddress, username='usr', password='pwd')
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command('sudo docker logs -f 16e --tail 100')
container_logs = ssh_stdout.read().decode("utf-8")
When reading the output it comes as empty string.
In the line where I defined 'ssh_stdin, ssh_stdout, ssh_stderr' when I debug it shows message as below
<paramiko.ChannelFile from <paramiko.Channel 0 (closed) -> <paramiko.Transport at 0x93ce2310 (cipher aes128-ctr, 128 bits) (active; 0 open channel(s))>>>
SSH connection works fine in the machine where I ran the code and I could see the logs.
I tried reading the 'ssh_stderr' as 'ssh_stderr.readlines()' and the output was as below
'sudo: no tty present and no askpass program specified '
I tried executing 'ls' command as below and that works fine!
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command('ls')
The ssh_stdout output comes below
Desktop Documents Downloads examples.desktop Music Pictures Public Templates Videos
Then the issue is with docker commands only!
For 'sudo' I need to provide a password. Not sure how to do this.
Python Version: 3.9.13
Paramiko Version: 2.11.0
Solution
The problem was due to a password request that comes immediately after 'sudo' command.
For this, I need to enter a Password and then the problem was solved!
def test_read_ssh():
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(IPAddress, username='usr', password='pwd')
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command('sudo docker logs -f 16e --tail 100', get_pty=True)
ssh_stdin.write('pwd\n')
ssh_stdin.flush()
container_logs = ssh_stdout.read().decode("utf-8")
Reference: https://www.youtube.com/watch?v=fVOFWehhc38
Thanks!
Answered By - KBNanda Answer Checked By - Mary Flores (WPSolving Volunteer)