shows as string in my text file
我是Python的笨蛋。但在Cisco等公司有丰富的CLI经验。我决定让python成为我的"转到"脚本工具。好吧,我第一次尝试甚至偷了大部分代码都失败得很惨…
我正在对主机列表执行ping操作。目的是1.验证它是活动的和2。获取IP
我在3.4版上做了一些调整后,我在网上得到的脚本开始工作了。
显示屏显示出我想要的完美。它所写的文件只是一行长的行,似乎
只是作为文本的一部分写入。这是屏幕显示和写入文件的代码和示例。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | import sys import os import platform import subprocess import threading import pexpect hosts_file = open("hosts.txt","r") lines = hosts_file.readlines() for line in lines: line = line.strip() ping = subprocess.Popen(["ping","-n","3",line],stdout = subprocess.PIPE,stderr = subprocess.PIPE) out, error = ping.communicate() out = out.strip() error = error.strip() output = open("PingResults.txt",'a') output.write(str(out)) output.write(str(error)) print(out.decode('utf-8')) print(error.decode('utf-8')) hosts_file.close() |
屏幕是完美的
1 2 3 4 | Pinging HOST7.foo [10.180.43.209] with 32 bytes of data: Reply from 10.180.43.209: bytes=32 time=81ms TTL=60 Reply from 10.180.43.209: bytes=32 time=56ms TTL=60 Reply from 10.180.43.209: bytes=32 time=56ms TTL=60 |
记事本++以可见的单行形式读取
(其他编辑器也是如此)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | b'Pinging host7.foo [10.180.43.11] with 32 bytes of data: Reply from 10.18.43.11: bytes=32 time=555ms TTL=60 Reply from 10.18.43.11: bytes=32 time=140ms TTL=60 Reply from 10.180.43.11: bytes=32 time=139ms TTL=60 Ping statistics for 10.180.43.11: Packets: Sent = 3, Received = 3, Lost = 0 (0% loss), Approximate round trip times in milli-seconds: Minimum = 139ms, Maximum = 555ms, Average = 278ms'b''b'Pinging host9.foo [10.180.43.25] with 32 bytes of data: Reply from |
帮我欧比-万-克诺比…你是我唯一的希望…
我在Ubuntu上的python2.7上再次检查了这段代码,添加了''或os.linesep后,它可以很好地工作。
在Python3.2上,subprocess.communication返回一个字节数组。
使用out.decode()应将其转换为字符串。
[下面是python 2.7]
strip()默认删除行尾字符。
1 2 | "Hello ".strip() |
收益率
1 | 'Hello' |
使用
1 2 | output.write(str(out + ' ')) |
或
1 | output.write(str(out + os.linesep)) |
[下面是python 3.x]
1 | output.write(out.decode() + os.linesep) |