我有这个脚本:
#!/usr/bin/python
import subprocess
import sys
HOST="cacamaca.caca"
COMMAND="display mac-address 0123-4567-8910"
ssh = subprocess.Popen(["ssh", "%s" % HOST, COMMAND],
shell=False,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
result = ssh.stdout.readlines()
if result == []:
error = ssh.stderr.readlines()
print >>sys.stderr, "ERROR: %s" % error
else:
print result因为输出有空格和不同的行,所以它还会打印回车符和新行,所以结果不是干净的:
'\r\n','cacamaca.caca\r\n',‘信息: VTY用户数上限为10,当前在线VTY用户数为\r\n’,‘。\r\n’,‘当前登录时间为2017-07-20 20:10:54+03:00 DST。\r\n’,'-------------------------------------------------------------------------------\r\n','MAC Address VLAN/VSI获知-来源类型\r\n','-------------------------------------------------------------------------------\r\n','0123-4567-8910 1234/-以太网-中继9动态\r\n','\r\n','-------------------------------------------------------------------------------\r\n',‘显示的项目总数=1 \n','\r\n','’
如何删除'\n‘和'\r\n’,或者至少用空格替换它们,以使结果看起来与原始结果相似?我确实读了很多关于这方面的答案,但都没有帮助。
发布于 2017-07-21 02:06:10
您的result变量是一个列表。我认为您希望将结果连接到一个字符串中并打印出来。您可以像这样使用str.join()来做到这一点
print ''.join(result)这将导致以下输出
cacamaca.caca
Info: The max number of VTY users is 10, and the number
of current VTY users on line is 2.
The current login time is 2017-07-20 20:10:54+03:00 DST.
-------------------------------------------------------------------------------
MAC Address VLAN/VSI Learned-From Type
-------------------------------------------------------------------------------
0123-4567-8910 1234/- Eth-Trunk9 dynamic
-------------------------------------------------------------------------------
Total items displayed = 1发布于 2017-07-21 02:06:29
您可以使用.strip()删除换行符,或使用.replace()替换它们,例如:
result = [x.strip() for x in result]输出:
['', 'cacamaca.caca', 'Info: The max number of VTY users is 10, and the number', 'of current VTY users on line is 2.', 'The current login time is 2017-07-20 20:10:54+03:00 DST.', '-------------------------------------------------------------------------------', 'MAC Address VLAN/VSI Learned-From Type', '-------------------------------------------------------------------------------', '0123-4567-8910 1234/- Eth-Trunk9 dynamic', '', '-------------------------------------------------------------------------------', 'Total items displayed = 1', '', '']发布于 2018-10-20 02:36:17
您可以使用以下代码删除'\n‘和'\r\n’。
with subprocess.Popen(["ssh", "%s" % HOST, COMMAND], shell=False) as ssh:
result = ssh.communicate()[0]
print(result)https://stackoverflow.com/questions/45222110
复制相似问题