Reputation: 21
I am creating a basic "whois" script, but it is not working. When I try to run it in the Linux terminal, it returns the error:
"TypeError: a bytes-like object is required, not 'str'" indicated in the line of code:
s.send(sys.argv[1]+"\r"+"\n")
.
consulta.py
#!/usr/share/python
import socket
import sys
import pyfiglet
ascii_banner = pyfiglet.figlet_format("WHOIS - Gustang")
print (ascii_banner)
reg = "whois.godaddy.com"
if len(sys.argv) == 2:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((reg, 43))
s.send(sys.argv[1]+"\r"+"\n")
resp = s.recv(1024)
print (resp)
else:
print ("Modo de Uso: IPv4 + Porta")
print ("Exemplo: 255.255.255.255 21")
Upvotes: 0
Views: 50
Reputation: 26993
You need to send bytes. The response will also be bytes.
With irrelevant parts of the code removed...
from socket import socket, AF_INET, SOCK_STREAM
from sys import argv
HOST = 'whois.godaddy.com'
PORT = 43
CONNECTION = HOST, PORT
CRLF = b'\r\n'
BUFSIZ = 16
def get_response(s: socket) -> str:
ba = bytearray()
while True:
ba.extend(s.recv(BUFSIZ))
if ba.endswith(CRLF):
break
return ba.decode()
if len(argv) == 2:
with socket(AF_INET, SOCK_STREAM) as s:
s.connect(CONNECTION)
s.send(f'{argv[1]}\r\n'.encode())
print(get_response(s))
Upvotes: 0