【问题标题】:How to skip lines when printing output from Paramiko SSH从 Paramiko SSH 打印输出时如何跳过行
【发布时间】:2021-04-08 02:20:51
【问题描述】:

所以我构建了一个程序,使用 tail -f 打印出我的 ubuntu 服务器的登录日志。 该程序使用 Paramiko 通过 ssh 连接并运行命令来跟踪日志。 该程序可以运行,但它会从服务器打印出不必要的 motd。

我尝试过使用 itertools 进行拼接。 尝试使用 next()。 还是不行。

这是我的代码:

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()

【问题讨论】:

    标签: python ssh paramiko


    【解决方案1】:

    您获得 MOTD 是因为您正在打开一个交互式 shell 会话。我认为你不需要那个,恰恰相反。

    改用SSHClient.exec_command

    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="")
    

    相关问题:


    强制警告:不要使用AutoAddPolicy - 这样做会失去对MITM attacks 的保护。如需正确解决方案,请参阅Paramiko "Unknown Server"

    【讨论】: