Skip to content
Advertisement

How to skip lines when printing output from Paramiko SSH

So I built a program that prints out the login logs of my ubuntu server using tail -f. The program uses Paramiko to connect via ssh and runs the command to tail the logs. The program works but it prints out the motd from the server which is unnecessary.

I’ve tried splicing using itertools. Tried using next(). Still doesn’t work.

Here’s my code:

import yaml, paramiko, getpass, traceback, time, itertools
from paramiko_expect import SSHClientInteraction

with open("config.yaml", "r") as yamlfile:
    cfg = yaml.load(yamlfile, Loader=yaml.FullLoader)

def main():

    command = "sudo tail -f /var/log/auth.log"

    try:

        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        server_pw = getpass.getpass("Enter the password for your account %s on %s:" % (cfg['ssh_config']['username'], cfg['ssh_config']['host']))
        sudo_pw = getpass.getpass("Enter the sudo password for %s on %s: " % (cfg['ssh_config']['username'], cfg['ssh_config']['host']))
        ssh.connect(hostname = cfg['ssh_config']['host'], username = cfg['ssh_config']['username'], port = cfg['ssh_config']['port'], password = server_pw)

        interact = SSHClientInteraction(ssh, timeout=10, display=False)
        interact.send(command)
        interact.send(sudo_pw + "n")

        with open(interact.tail(line_prefix=cfg['ssh_config']['servername']+': ')) as tail:
            for line in itertools.islice(tail, 17, None):
                print(line)

    except KeyboardInterrupt:
            print('Ctrl+C interruption detected, stopping tail')
    except Exception:
        traceback.print_exc()
    finally:
        try:
            ssh.close()
        except:
            pass

if __name__ == '__main__':
       main()

Advertisement

Answer

You get MOTD because you are opening an interactive shell session. I do not think you need that, quite on the contrary.

Use SSHClient.exec_command instead:

stdin, stdout, stderr = ssh.exec_command(command, get_pty=True)

stdin.write(sudo_pw + "n")
stdin.flush()

for line in iter(stdout.readline, ""):
    print(line, end="")

Related questions:


Obligatory warning: Do not use AutoAddPolicy – You are losing a protection against MITM attacks by doing so. For a correct solution, see Paramiko “Unknown Server”.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement