Python 使用 Telnet 进行线程化

Python threading with Telnet

我正在尝试通过 telnet 连接到多个交换机并获得使用 CPU 的输出。一个线程工作并显示正确的 CPU 用法。第二个线程什么都不做。如何让两个线程使用与第一个相同的命令。

import time
import telnetlib
import threading


Host1 = '192.168.1.42'
username1 = 'root'

Host2 = '192.168.86.247'
username2 = 'root'

tn = telnetlib.Telnet(Host1)

def switch1():
   tn.write(username1.encode("ascii") + b"\n")

   #confirms connection
   print("connected to %s" % Host1)

   #send command
   tn.write(b"sh cpu-usage\n")
   time.sleep(2)

   #reads clean i/o
   output = tn.read_very_eager()


   #print the command
   print (type("output"))
   print(output)
   print("done")



def switch2():
   #input username
   tn.write(username2.encode("ascii") + b"\n")
   tn.write(password.encode("ascii") + b"\n")

   #confirms connection
   print("connected to %s" % Host2)

   #send command
   tn.write(b"sh cpu-usage\n")
   time.sleep(2)

   #reads clean i/o
   output1 = tn.read_very_eager()


   #print the command
   print (type("output"))
   print(output1)
   print("done")



t1 = threading.Thread(target=switch1)



t2 = threading.Thread(target=switch2)





t1.start()
t2.start()

这是输出

[Command: python -u C:\Users\AKPY7Z\Documents\Threading\threadcpu.py]
connected to 192.168.1.42
connected to 192.168.86.247
<class 'str'><class 'str'>
b'ugoonatilaka\r\r\n         ^\r\n% Invalid input detecte'
done
b"\r\r\nswitch_a login: root\r\njanidugoonatilaka\r\nsh cpu-usage\r\n*password*\r\nifconfig\r\n\r\r\nSwitch version 2.01.2.7 03/29/18 10:36:11\r\nswitch_a>janidd at '^' marker.\r\n\r\nswitch_a>sh cpu-usage\r\r\nNow CPU Usage 17%\r\nMax CPU Usage 18%\r\nswitch_a>*password*\r\r\n         ^\r\n% Invalid input detected at '^' marker.\r\n\r\nswitch_a>ifconfig\r\r\n         ^\r\n% Invalid input detected at '^' marker.\r\n\r\nswitch_a>"
done
[Finished in 2.678s]<class 'str'>
b'\r\n'
done
[Finished in 293.505s]

您只创建到一个交换机的连接

tn = telnetlib.Telnet(Host1)

之后您在两个函数中使用相同的连接,并且每个函数都尝试使用不同的用户名和密码 - 并且可能只有其中一个函数为此开关使用了正确的值。

你应该在一个函数中 运行 Telnet(Host1) 而在另一个函数中 Telnet(Host2) 他们会尝试访问不同的开关。

def switch1():
   tn = telnetlib.Telnet(Host1)
   # ... rest ...

def switch2():
   tn = telnetlib.Telnet(Host2)
   # ... rest ...

顺便说一句:

您可以创建一个函数并运行它使用不同的参数

import time
import telnetlib
import threading


host1 = '192.168.1.42'
username1 = 'root'

host2 = '192.168.86.247'
username2 = 'root'

def switch(host, username, password=None):
    tn = telnetlib.Telnet(host)
   
    tn.write(username.encode("ascii") + b"\n")
    if password:
       tn.write(password.encode("ascii") + b"\n")
        
    # confirms connection
    print("connected to %s" % host)

    # send command
    tn.write(b"sh cpu-usage\n")
    time.sleep(2)

    # reads clean i/o
    output = tn.read_very_eager()

    # print the command
    print (type("output"))
    print(output)
    print("done")

t1 = threading.Thread(target=switch, args=(host1, username1, password))
t2 = threading.Thread(target=switch, args=(host2, username2, None))

t1.start()
t2.start()