简体   繁体   English

Python3.10脚本中的TypeError

[英]TypeError in Python3.10 script

Hello Friends,你好朋友,

I am new to programming and I am trying to do network automation task using python but ran with type error while running the below given script!!!我是编程新手,我正在尝试使用 python 执行网络自动化任务,但在运行以下给定脚本时出现类型错误!!! Thanks in advance for your help !在此先感谢您的帮助 !

I AM STUCK AT SAME KIND OF ERROR, CAN YOU GUYS PLEASE HELP ME OUT HOW TO FIX THIS?我遇到了同样的错误,你们能帮我解决这个问题吗?

durai@durai-virtual-machine:~/Network Automation$ python3 session_details.py 
devices list: ['1.1.1.1', '2.2.2.2', '6.6.6.6', '7.7.7.7', '', '']
establishing telnet session: 1.1.1.1 cisco cisco
--- connected to:  1.1.1.1
--- getting version information
Traceback (most recent call last):
  File "/home/durai/Network Automation/session_details.py", line 82, in <module>
    device_version = get_version_info(session)
  File "/home/durai/Network Automation/session_details.py", line 65, in get_version_info
    version_output_parts = version_output_lines[1].split(',')
**TypeError: a bytes-like object is required, not 'str'**
durai@durai-virtual-machine:~/Network Automation$

THE BELOW IS THE BLOCK OF CODE WHERE I AM GETTING ERROR !下面是我出错的代码块!

#-----------------------------------------------------------------------
def get_version_info(session):

    print ('--- getting version information')

    session.sendline('show version | include Version')
    result = session.expect(['>', pexpect.TIMEOUT])

    # Extract the 'version' part of the output
    version_output_lines = session.before.splitlines()
    version_output_parts = version_output_lines[1].split(',')
    version = version_output_parts[2].strip()

    print ('--- got version: ', version)
    return version

#-----------------------------------------------------------------------

FULL CODE FOR YOUR REFERENCE:完整代码供您参考:

#!/usr/bin/python

import re
import pexpect

#-----------------------------------------------------------------------
def get_devices_list():

    devices_list = []
    file = open('devices', 'r')

    for line in file:
        devices_list.append( line.rstrip() )

    file.close()

    print ('devices list:', devices_list)
    return devices_list

#-----------------------------------------------------------------------
def connect(ip_address, username, password):

    print ('establishing telnet session:', ip_address, username, password)
    telnet_command = 'telnet ' + ip_address

    # Connect via telnet to device
    session = pexpect.spawn('telnet ' + ip_address, timeout=20)
    result = session.expect(['Username:', pexpect.TIMEOUT])

    # Check for error, if so then print error and exit
    if result != 0:
        print ('!!! TELNET failed creating session for: ', ip_address)
        exit()

    # Enter the username, expect password prompt afterwards
    session.sendline(username)
    result = session.expect(['Password:', pexpect.TIMEOUT])

    # Check for error, if so then print error and exit
    if result != 0:
        print ('!!! Username failed: ', username)
        exit()

    session.sendline(password)
    result = session.expect(['>', pexpect.TIMEOUT])

    # Check for error, if so then print error and exit
    if result != 0:
        print ('!!! Password failed: ', password)
        exit()

    print ('--- connected to: ', ip_address)
    return session

#-----------------------------------------------------------------------
def get_version_info(session):

    print ('--- getting version information')

    session.sendline('show version | include Version')
    result = session.expect(['>', pexpect.TIMEOUT])

    # Extract the 'version' part of the output
    version_output_lines = session.before.splitlines()
    version_output_parts = version_output_lines[1].split(',')
    version = version_output_parts[2].strip()

    print ('--- got version: ', version)
    return version

#-----------------------------------------------------------------------

devices_list = get_devices_list()    # Get list of devices

version_file_out = open('version-info-out', 'w')

# Loop through all the devices in the devices list
for ip_address in devices_list:

    # Connect to the device via CLI and get version information
    session = connect(ip_address, 'cisco', 'cisco')
    device_version = get_version_info(session)

    session.close()  # Close the session

    version_file_out.write('IP: '+ip_address+'  Version: '+device_version+'\n')

# Done with all devices and writing the file, so close
version_file_out.close()

Python has two different kinds of strings. Python 有两种不同的字符串。 Normal strings are Unicode, where the individual characters are several bytes long, to handle Unicode characters.普通字符串是 Unicode,其中单个字符长几个字节,用于处理 Unicode 字符。 Many activities (like networking) need to use byte strings, which are written b"abc" .许多活动(如网络)需要使用字节字符串,它们被写成b"abc"

That's the problem here.这就是这里的问题。 The pexpect module is returning a byte string. pexpect模块正在返回一个字节字符串。 So, in this line:所以,在这一行:

version_output_parts = version_output_lines[1].split(',')

version_output_parts is a byte string, but ',' is a Unicode string, and you can't mix them. version_output_parts是字节串,而','是 Unicode 字符串,不能混用。 So, you can either keep it bytes and do this:因此,您可以保留它的字节并执行以下操作:

version_output_parts = version_output_lines[1].split(b',')

or you can convert it to a Unicode string:或者您可以将其转换为 Unicode 字符串:

version_output_parts = version_output_parts.decode('utf-8')
version_output_parts = version_output_lines[1].split(b',')

It depends on how much you need to do with the parts.这取决于您需要对零件进行多少处理。

Its the part where you extract the version, is bugged.它是您提取版本的部分,被窃听。

Try using print statements as demonstrated below to check the data types of your variables at each step.尝试使用如下所示的打印语句在每个步骤中检查变量的数据类型。

This Error suggests that you are using a method which is not available for the given data type eg calling a string method on an array or so on.此错误表明您正在使用对给定数据类型不可用的方法,例如在数组上调用字符串方法等。

def get_version_info(session): def get_version_info(会话):

print ('--- getting version information')

session.sendline('show version | include Version')
result = session.expect(['>', pexpect.TIMEOUT])

# Extract the 'version' part of the output
version_output_lines = session.before.splitlines()

# print(version_output_lines)
version_output_parts = version_output_lines[1].split(',')
# print(version_output_parts)
version = version_output_parts[2].strip()
# print(version) 
print ('--- got version: ', version)
return version

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM