如何在命令提示符下打印输出时以清晰的格式打印输出

时间:2019-10-21 09:38:51

标签: python python-3.x network-programming

  • 我正在尝试通过SSH进入客户端并运行命令,但是输出的格式未设置,如服务器的CLI所示。
  • 我试图使用打印功能并试图写入文件并检查了许多文章,但我想我缺少要寻找的东西。

    import paramiko
    import sys
    
    hn = "valid IP Address"  #hostname of the client
    ssh_client = paramiko.SSHClient()
    ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh_client.connect (hostname = hn,username='randomUsername',password='randomPassword')
    print ("Connected to %s \n" % (hn))
    
    stdin, stdout, stderr = ssh_client.exec_command("ping 8.8.8.8 -c 4")
    stdout = stdout.readlines()
    print (stdout)
    
    stdin, stdout, stderr = ssh_client.exec_command("ping 8.8.4.4 -c 4")
    stdout = stdout.readlines()
    print (stdout)
    
  • 我如何像这样打印输出并写入文件? 当前输出是这样的

    ['PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.\n', '64 bytes from 8.8.8.8: icmp_req=1 ttl=57 time=21.3 ms\n', '64 bytes from 8.8.8.8: icmp_req=2 ttl=57 time=21.0 ms\n', '64 bytes from 8.8.8.8: icmp_req=3 ttl=57 time=21.0 ms\n', '64 bytes from 8.8.8.8: icmp_req=4 ttl=57 time=21.2 ms\n', '\n', '--- 8.8.8.8 ping statistics ---\n', '4 packets transmitted, 4 received, 0% packet loss, time 3003ms\n', 'rtt min/avg/max/mdev = 21.041/21.173/21.313/0.159 ms\n']
    ['PING 8.8.4.4 (8.8.4.4) 56(84) bytes of data.\n', '64 bytes from 8.8.4.4: icmp_req=1 ttl=57 time=19.4 ms\n', '64 bytes from 8.8.4.4: icmp_req=2 ttl=57 time=19.1 ms\n', '64 bytes from 8.8.4.4: icmp_req=3 ttl=57 time=18.8 ms\n', '64 bytes from 8.8.4.4: icmp_req=4 ttl=57 time=19.0 ms\n', '\n', '--- 8.8.4.4 ping statistics ---\n', '4 packets transmitted, 4 received, 0% packet loss, time 3003ms\n', 'rtt min/avg/max/mdev = 18.819/19.135/19.470/0.233 ms\n']
    
  • 但是我需要像这样打印

    ping 8.8.8.8
    PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
    64 bytes from 8.8.8.8: icmp_seq=1 ttl=56 time=3.79 ms
    64 bytes from 8.8.8.8: icmp_seq=2 ttl=56 time=3.58 ms
    64 bytes from 8.8.8.8: icmp_seq=3 ttl=56 time=14.8 ms
    64 bytes from 8.8.8.8: icmp_seq=4 ttl=56 time=3.37 ms
    --- 8.8.8.8 ping statistics ---
    4 packets transmitted, 4 received, 0% packet loss, time 3005ms 
    rtt min/avg/max/mdev = 3.375/6.409/14.891/4.899 ms
    

谢谢您的帮助。

****解决了**** 对于我在标准输出中:     打印(i)

1 个答案:

答案 0 :(得分:0)

Stdout是一个字符串列表-遍历字符串并打印每个字符串,而不是打印整个列表。

for i in stdout:
    print(i) # you can add end='' if you want to remopve the double spacing -> print(i, end='')

要写入文件,我建议从reading and writing files

上的python文档开始