我正在编写一个脚本以ssh连接到我拥有的所有开关,运行命令,然后获取输出并将其发送到文本文件。但是,我得到的输出需要过滤到一些有用的东西。我只需要知道接口及其所在的VLAN。我编写了另一个脚本来提取第一个脚本创建的文本文件,以进行文本过滤,但这还不够。我将代码发布到两者,以便您了解完整的上下文
f = open("vlancheck.txt", "a+")
hostname = "host here"
port = 22
username = getpass.getpass(prompt="Username: ") #used for hiding input
password = getpass.getpass()
command = "show interface status | e disabled"
string = " "
ssh = paramiko.SSHClient() #starts ssh client
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) #generates ssh key for all unknown hosts
ssh.connect(hostname, port=port, username=username, password=password) # logs in with the credentials stored in variables
stdin, stdout, stderr = ssh.exec_command(command) #manages input,output, and error data generated by the command sent
output = stdout.readlines() #reads the output as a list
print("\n".join(output))
f.write(hostname)
f.writelines(output) # writes the output as a list
f.close()
open("truncated.txt" , "w+").writelines([line for line in open("vlancheck.txt") if "Gi" in line])
我正在使用cisco开关,这是我通过过滤器脚本获得的输出:
Gi1/0/6 connected 708 a-full a-100 10/100/1000BaseTX
Gi1/0/9 connected 708 a-full a-100 10/100/1000BaseTX
这很好,但我想将其简化为:
Gi1/0/6 connected 708
Gi1/0/9 connected 708
答案 0 :(得分:0)
因此,假设我正确理解了您的问题,并且您提供的代码...您的输出Gi1/0/6 connected 708 a-full a-100 10/100/1000BaseTX
会显示在以下行中:print("\n".join(output))
假设您的输出变量是一个列表,我在下面创建了一个示例:
output = ['Gi1/0/6','connected','708', 'a-full','a-100','10/100/1000BaseTX']
print(' '.join(output[0:3]))
返回:
Gi1/0/6 connected 708
答案 1 :(得分:0)
如果要此输出Gi1/0/9 connected 70
使用regix re.sub()
这就是您的使用方式。
print re.sub(' +', ' ',output)
它将消除您使用的变量中的重复空格
答案 2 :(得分:0)
感谢您的帮助。我确实自己弄清楚了。我将发布我的工作。这可能不是最好的,但绝对可以!!
with open("hosts.txt") as l:
line = l.readline()
print(line)
while line is not None:
for host in line:
host = "".join(line)
host = host.strip('\n')
#print(host)
ssh = paramiko.SSHClient() #starts ssh client
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) #generates ssh key for all unknown hosts
ssh.connect(host, port=port, username=username, password=password) # logs in with the credentials stored in variables
stdin, stdout, stderr = ssh.exec_command(command) #manages input,output, and error data generated by the command sent
output = stdout.readlines() #reads the output as a list
#print("\n".join(output))
f.write(host + "\n")
for i in output:
if i.startswith("Gi"):
f.writelines(i[0:46] + "\n") # writes the output as a list
line = l.readline()