Python 3,telnet 自动化

标签 python automation telnet switching

我正在做一个项目,该项目是从多个交换机收集某些信息。请记住,我是 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,telnet 自动化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28987822/

相关文章:

C# 如何在一定时间后停止程序?

node.js - Telnet:Windows 7 上的本地主机无法连接到本地主机

python - 来自 python 中的 telnet session 的 Telnet

python - Selenium python 卡在这条线上

javascript - Protractor 处理异常;异步弹出; Javascript

python - 如何测试每个特定的数字或字符

powershell - Azure Runbook 输出到电子邮件

windows - 使用批处理脚本在 Windows 7 上自动进行 telnet 端口测试

python - 如何按 MultiIndex 和按值对 Pandas DataFrame 进行排序?

python - 是否有与 Python 的 for-else 语句等效的 Fortran 语句?