首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python 2.7 telnetlib For Loop

Python 2.7 telnetlib For Loop
EN

Stack Overflow用户
提问于 2017-04-26 04:43:33
回答 2查看 1.3K关注 0票数 0

我正在用python编写一个简单的脚本,用于telnet多台cisco交换机并添加vlans。我正在UNET实验室或最新的EVE-NG中测试我的脚本。当我使用FOR循环远程登录到多个交换机并从with in循环调用tn =telnetlib.Telnet(主机)时,它只远程登录到变量HOST中的最后一个值,即10.1.1.7

这是我的代码,

代码语言:javascript
复制
#!/usr/bin/env python

import getpass
import sys
import telnetlib

user = raw_input("Enter your telnet username: ")
password = getpass.getpass()


for h in range (2,8):
    print "Telnet to host" + str(h)
    HOST = "10.1.1." + str(h)
    tn = telnetlib.Telnet(HOST)

    tn.read_until("Username: ")
    tn.write(user + "\n")
    if password:
        tn.read_until("Password: ")
        tn.write(password + "\n")

    tn.write("conf t\n")

    for n in range (10,20):
        tn.write("vlan " + str(n) + "\n")
EN

回答 2

Stack Overflow用户

发布于 2018-01-31 20:54:25

下面的代码对我来说很有效。把你所有的in放在一个工作表中(IP_test.txt)。

代码语言:javascript
复制
    import getpass
    import sys
    import telnetlib
    user = "YOURUSER"
    password = "YOURPASSWORD"
    with open('IP_test.txt') as file:
            for HOST in file:
        tn = telnetlib.Telnet(HOST)
        tn.read_until("login: ")
        tn.write(user + "\n")
        if password:
            tn.read_until("Password: ")
            tn.write(password + "\n")
            tn.write("Command1\n")
            tn.write("Command2\n")
            print(tn.read_all())
票数 0
EN

Stack Overflow用户

发布于 2019-02-24 14:39:44

下面的python脚本适用于我的相同目的

代码语言:javascript
复制
#!/usr/bin/env python3
import getpass
import telnetlib
user = input("Enter your Telnet Username: ")
password = getpass.getpass()

DeviceList=open('/home/tt/Hostname.txt')
for HOST in DeviceList:
    print('Configuring on Device : ',HOST)
    tn = telnetlib.Telnet(HOST)
    tn.read_until(b"Username: ")
    tn.write(user.encode('ascii') + b"\n")
    if password:
        tn.read_until(b"Password: ")
        tn.write(password.encode('ascii') + b"\n")
        tn.write(b"enable\n")
        EnPass=input('Enter your Enable password : ')
        tn.write(EnPass.encode('ascii')+b'\n')
        c=open('/home/tt/Commands.txt')
        for i in c:
            tn.write(i.encode('ascii')+b'\n')
        c.close()
        print(tn.read_all().decode('ascii'))
        tn.close()
DeviceList.close()}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43620591

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档