gpt4 book ai didi

Python 3,远程登录自动化

转载 作者:太空宇宙 更新时间:2023-11-04 03:36:09 26 4
gpt4 key购买 nike

我正在做一个项目,该项目是从多个交换机收集某些信息。请记住我是 python 和编程的新手。我想要做的是:拥有一个包含我的开关名称的 .txt 文件。
然后遍历该列表,运行一些命令,并保存输出。

到目前为止,我有以下内容,可在单个开关上运行。正如您在评论中看到的那样,我试图打开我的 list.txt 并循环遍历它,但由于它在列表中,我的程序无法运行(输出:['switchname-1'])我如何阅读我的列表.txt 并将变量作为纯文本获取,例如。没有所有列表字符的 switchname-1 ?

import sys
import telnetlib
import time

password = "password"
command = "show interface status"

##with open ("list.txt", "r") as devicelist:
## hostlist = []
## hostlist=devicelist.readlines()
## print(hostlist)
hostlist= [ ("switchname-1","",""),]

for host in hostlist:

cmd1 = "enable"
tn = telnetlib.Telnet(host[0])

time.sleep(2)
tn.read_until(b"Password: ")
tn.write(password.encode('ascii') + b"\n")
time.sleep(2)
tn.write(cmd1.encode('ascii') + b"\n")
time.sleep(2)
tn.write(password.encode('ascii') + b"\n")
time.sleep(2)
tn.write(command.encode('ascii') + b"\n")
time.sleep(2)
tn.write(b"\n")
time.sleep(2)
tn.write(b"\n")
time.sleep(2)
tn.write(b"exit\n")
lastpost = tn.read_all().decode('ascii')
op=open ("output.txt", "w")
op.write(lastpost)
print("writing to file")
op.close()
print(lastpost)
tn.close()

我也在尝试找出是否有某种方法可以只打印开关的最后输出而不是 lastpost = tn.read_all().decode('ascii')发布整个 telnet session ?

最佳答案

工作代码:

import sys
import telnetlib
import time

password = "pw"
command = "sh ver"
term = "term len 0"

data = open("hostlist.txt")
for line in data:
cmd1 = "enable"
tn = telnetlib.Telnet(line.rstrip())
tn.set_debuglevel(1)
time.sleep(2)
tn.read_until(b"Password: ")
tn.write(password.encode('ascii') + b"\n")
time.sleep(2)
tn.write(cmd1.encode('ascii') + b"\n")
time.sleep(2)
tn.write(password.encode('ascii') + b"\n")
time.sleep(2)
tn.write(term.encode('ascii') + b"\n")
tn.write(command.encode('ascii') + b"\n")
time.sleep(2)
tn.write(b"\n")
time.sleep(2)
tn.write(b"\n")
time.sleep(2)
tn.write(b"exit\n")
lastpost = tn.read_all().decode('ascii')
print(lastpost)
op=open ("output.txt", "a").write(lastpost)
tn.close()

关于Python 3,远程登录自动化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28987822/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com