getpass.getpass() function in Python not working? - python

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

Related

How to Have "Destination Host Unreachable" when pinging return a value of 1 and not 0

I am using python to code a program that will ping a device, and do nothing if it gets a response back from the device, but if it does not receive any response, it will send me an email to notify me that the device may be down. However, as has been mentioned on here before, when the response from the ping is "Destination Host Unreachable," the return value is 0, which is the same as if it received a response. So what I'm looking for is help with how to discern the Destination Host Unreachable from the actual response so I can have an email sent to me under that condition (since it means the device is most likely down).
import platform
import subprocess
import smtplib
import time
#Delay to wait for Rigs to Boot
#time.sleep(600)
a = 1
while 1==1:
#Ping other PC's
def myping(host):
parameter = '-n' if platform.system().lower()=='windows' else '-c'
command = ['ping', parameter, '1', host]
response = subprocess.call(command)
if response == 0:
return True
#Will Send email if response from ping is false (aka not pingable/down)
else:
gmail_user = 'email'
gmail_password = 'password'
sent_from = gmail_user
to = ['recepient']
subject = 'subject'
body = 'body'
email_text = """\
From: %s
To: %s
Subject: %s
%s
""" % (sent_from, ", ".join(to), subject, body)
try:
smtp_server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
smtp_server.ehlo()
smtp_server.login(gmail_user, gmail_password)
smtp_server.sendmail(sent_from, to, email_text)
smtp_server.close()
print ("Email sent successfully!")
except Exception as ex:
print ("Something went wrong….",ex)
#delay so i dont recieve spam emails while the 'while' loop runs
time.sleep(43000)
print(myping("ip to ping"))
Thank you for the help in advance.
You obviously can't change the behavior of ping. However, you can certainly use subprocess.check_output, which returns the output of the command, and parse that.
Using ping like this is not particularly useful. There are many reasons why you can't reach a remote host. Perhaps your local network is down, or your router has died, or your cable has been unplugged.

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.

print message from python program that started in background

I made a python program thats is called when I connect to a ppp network.The app requests www.noip.com to link any new IP to a Host I created in their website.
/etc/ppp/ip-up.d/noip.sh #this script calls my python app
The script runs fine when I connect to ppp, the python app is triggered and does change my IP addr on www.noip.com, but I'm not able to print messages to the console using just print. I have a few print statements in my app that only work if I run the app from the command line like ./myapp.py
How to show messages if my python app is called from background?
here is my Python code:
#!/usr/bin/python
import requests
import netifaces as ni
user = 'xxxxxxx'
pswd = 'xxxxxxx'
ni.ifaddresses('ppp0')
ip = ni.ifaddresses('ppp0')[2][0]['addr']
myhostname = 'xxxxxxx'
payload = {'hostname' : myhostname , 'myip' : ip}
r = requests.get("http://dynupdate.no-ip.com/nic/update", params=payload, auth=(user,pswd))
print " "
if "good" in r.text:
print "Hello ", user, "!"
print "your IP was successfully updated to:", ip
print myhostname, "is up and running!"
if "nochg" in r.text:
print "Hello", user, "!"
print "Your IP", ip, "is still active, no change needed"
if "nohost" in r.text:
print "The given Host name", myhostname, "does not exist under specified account"
print "Please review your Host name and try again"
if "badauth" in r.text:
print "Login and/or Username incorrect"
print "Please correct your credentials and try again"
if "911" in r.text:
print "Sorry for the incovenience but we are experiencing some problems right now"
print "Please try again later"
print "noip.com says:", r.text
print " "
The simplest to do this is to make the output go to a file in noip.sh:
python myapp.py > /tmp/myapp.out
Then when you want to see the output,
tail -f /tmp/myapp.out

Connection to Twitch IRC fails without good reason in Python

I am currently trying to read messages cat channels Twitch. For this, I have read some guides and I learned it had to go through the IRC Twitch. I then found a few lines of simple code.
import socket
import string
HOST="irc.twitch.tv"
PORT=6667
NICK="TwitchUsername"
IDENT="TwitchUsername"
REALNAME="TwitchUsername"
CHANNEL="#ChannelNameHere"
PASSWORD="OAuth Password here" #From http://twitchapps.com/tmi/
readbuffer=""
s=socket.socket( )
s.connect((HOST, PORT))
s.send("PASS %s\r\n" % PASSWORD)
s.send("NICK %s\r\n" % NICK)
s.send("USER %s %s bla :%s\r\n" % (IDENT, HOST, REALNAME))
s.send("JOIN %s\r\n" % CHANNEL)
while 1:
readbuffer=readbuffer+s.recv(1024)
temp=string.split(readbuffer, "\n")
readbuffer=temp.pop( )
for line in temp:
line=string.rstrip(line)
line=string.split(line)
if len(line) > 3:
print line
if(line[0]=="PING"):
s.send("PONG %s\r\n" % line[1])
However, authentication does not proceed as planned, since I get the following message:
[':tmi.twitch.tv', 'NOTICE', '*', ':Login', 'unsuccessful']
I am using a valid OAuth Chat Password, and I see no reason that justifies this failure. Do you also have an error when you try with your username? Or do you have an idea of ​​the problem please?
Your OAuth password needs to be sent as:
PASS oauth:twitch_oauth_token
which means that if you are putting in your token in the PASSWORD variable without the oauth: prefix, you should amend the pass line to:
s.send("PASS oauth:%s\r\n" % PASSWORD)
I was seeing the same :tmi.twitch.tv NOTICE * :Error logging in.
As noted in the readme "Your nickname must be your Twitch username in lowercase".
My issue was not making the NICK exactly my twitch username in lowercase (Not a very informative notice. So hopefully this saves someone else some time...).

Python script progress email

I have a Python script that loops through a list of 8 different machines and does a copy, execute, and test. I would like to receive an email after each loop. **I'm not sure what to google for this. I would appreciate any ideas that will help me with my task.
I am aware of the smtplib module, just not how to perform a certain task with it.
I did indeed check the handy search engine and found no previous questions that provided answers
Question: how would one break in the middle of a loop, send an email, then continue with the loop??????
I have an email when the script starts and an email when the script ends. I just want to be notified as the script progresses or if it fails.
Thank you in advance.
You're looking for Python's smtp library.
The example from the documentation is this:
import smtplib
def prompt(prompt):
return raw_input(prompt).strip()
fromaddr = prompt("From: ")
toaddrs = prompt("To: ").split()
print "Enter message, end with ^D (Unix) or ^Z (Windows):"
# Add the From: and To: headers at the start!
msg = ("From: %s\r\nTo: %s\r\n\r\n"
% (fromaddr, ", ".join(toaddrs)))
while 1:
try:
line = raw_input()
except EOFError:
break
if not line:
break
msg = msg + line
print "Message length is " + repr(len(msg))
server = smtplib.SMTP('localhost')
server.set_debuglevel(1)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
Use the built-in email package to create your message if there's anything nonstandard you need to do with MIMEtypes/etc. Use the built-in smtplib package to send it (and create it if you don't have to do anything fancy).

Categories

Resources