【问题标题】:Python 3 - TypeError: can only concatenate str (not "bytes") to strPython 3 - TypeError:只能将 str (不是“字节”)连接到 str
【发布时间】:2019-07-24 09:19:04
【问题描述】:

我有这个错误的代码,找不到修复方法。

49         os.system('powershell -enc 
    '+base64.b64encode(addpermissions.encode('utf_16_le')))   
    . 
    .
    .
     137 HexRegHash, HexRegSysk, jd, skew1, gbg, data = getRegistryValues(HexRID)

我有这个错误:

    Traceback (most recent call last):
      File "hash.py", line 137, in <module>
        HexRegHash, HexRegSysk, jd, skew1, gbg, data = 
    getRegistryValues(HexRID)
      File "hash.py", line 49, in getRegistryValues
        os.system('powershell -enc 
    '+base64.b64encode(addpermissions.encode('utf_16_le')))
    TypeError: can only concatenate str (not "bytes") to str

【问题讨论】:

    标签: python python-3.x windows


    【解决方案1】:

    base64.b64encode 生成字节流,而不是字符串。因此,要使您的串联工作,您必须先使用str(base64.b64encode(addpermissions.encode('utf_16_le'))) 将其转换为字符串

    b64cmd = base64.b64encode(cmd.encode('utf_16_le')).decode('utf-8')
    os.system('powershell -enc ' + b64cmd)
    

    编辑:正常的字符串转换不适用于 os.system,而是使用 decode('utf-8')

    【讨论】:

    • 它会产生如下错误:无法处理命令。使用 -EncodedCommand 指定的值未正确编码。对于该值,必须使用 Base64 编码。
    • 看起来os.system 的结果有问题。您必须将其显式转换为 utf8 字符串,而不是调用 str 构造函数。 base64.b64encode(addpermissions.encode('utf_16_le')).decode('utf-8')。我已经更新了我原来的帖子
    • str() 没有指定编码只返回对象的__str__(或其他__repr__)方法的结果,对于bytes 对象是它的repr(例如"b'spam'") . b64encode 的结果可以解码为'ascii',尽管 UTF-8 可以工作,因为它扩展了 ASCII。
    猜你喜欢
    • 2021-03-11
    • 1970-01-01
    • 1970-01-01
    • 2021-11-07
    • 2021-06-22
    • 2019-05-13
    • 2021-02-22
    • 2020-10-20
    相关资源
    最近更新 更多