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
Related
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.
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
I am trying to telnet into a cisco ios-xr router and gather command output.
I have tested that the below code successfully connects to the router and executes the command, however it seems that neither print tn.read_all() nor tn.read_very_eager() works. They do not print anything. Am I missing anything obvious here?
#!/usr/bin/env python
import sys
import telnetlib
import time
HOST = "10.62.53.34"
PORT = "17006"
user = "cisco"
password = "cisco"
tn = telnetlib.Telnet(HOST,PORT)
print "Telnetting to", HOST, "#",PORT
tn.write("\n")
tn.write(user + "\n")
tn.write(password + "\n")
#print("I am in")
tn.write("show runn\n")
tn.write("exit \n")
print tn.read_all()
tn.close()
though this question is from february, i'll post my answer for a potential future googler.
i fixed a similar problem when i realized that:
print tn.read_all()
...is valid in python 2 (see the example at the bottom of https://docs.python.org/2/library/telnetlib.html), but not in python 3 (https://docs.python.org/3.6/library/telnetlib.html).
for python 3, the correct syntax would be:
print(tn.read_all())
Is there a way for Python to send ping and get results, 1 or 0, without the console popping out? I need the results for UI change in style.
I've been trying import os and it still shows the console, as well as subprocess.
This is the sample I get from other questions but I can't get the console not to show.
import os
hostname = "google.com"
response = os.system("ping-c 1 " + hostname)
if response == 0:
print hostname, 'is up!'
else:
print hostname, 'is down!'
Thanks for the help.
I have having a problem with one of my university projects. We are doing sockets and UDP at the moment. Anyway so we had to make a very simple program, server, client, password name verification.
He wanted us to make a log of things, and I created a module with methods to write to a log file, this works fine. I have called it from different places and it always works. The only time it does not work is when called from the server.
import datetime
###Appends the message to the server log with the current date and time
def AddToLogServer(message):
f = open('Log_Server', 'a')
time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
f.write(time +" " + message +"\n")
f.close()
###Appends the message to the client log with the current date and time
def AddToLogClient(message):
f = open('Log_Client', 'a')
time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
f.write(time +" " + message +"\n")
f.close()
This is the log creations. Works fine.
import socket
import sys
import Passwords
import getpass
import Log
###Create a connectionless network socket.
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
###Maximum size data.
MAX = 65535
PORT = 1060
if sys.argv[1:] == ['server']:
###Set server ip
ip = '127.0.0.1'
try:
s.bind((ip, PORT))
except:
###If the server fails to start this error message and the server should end.
print "There is an error, perhaps the ip is already being used."
s.close()
sys.exit(1)
###Add to the server log that the server has started.
Log.AddToLogServer("The server is up with the ip " + ip)
print 'Server is up and listening at', s.getsockname()
###Listen for a client to send data to the server.
while True:
data, address = s.recvfrom(MAX)
Passwords.getPasswordsAndUsers()
###Compare the name inputted to the ones in the user list
i = Passwords.findUser(data)
###Update client log
Log.AddToLogServer(address[0] + " Inputted the name " + data)
s.sendto(str(i), address)
data, address = s.recvfrom(MAX)
t = Passwords.checkPassword(data,i)
###if the password matched the user print out the correct message and send a message to the client
if t == 1:
Log.AddToLogServer(address[0] + " Inputted the correct password for that user")
print address[0] + " Has successfully entered the correct User and Password"
s.sendto("The name and password were correct", address)
###if the password did not match the user print out the correct message and send a message to the client
else:
Log.AddToLogServer(address[0] + " Inputted an incorrect password for that user")
print address[0] + " Has failed to provide the correct Password for the inputted User"
s.sendto("The password did not match the name", address)
elif sys.argv[1:] == ['client']:
###Takes in the ip and name as inputs.
serverIp = raw_input("Please enter the server ip : ");
username = raw_input("Enter your first name please: ");
### Attempts to send to the server with the given ip
try:
s.sendto(username, (serverIp, PORT))
except:
###If the send fails then an error is shown and it finishes the execution.
print "There was a problem sending to the server"
s.close()
sys.exit(1)
###Attempt to relieve data from the server, if the client does not then write the appropriate message.
try:
data, address = s.recvfrom(MAX)
except:
print "There was a problem receiving from the server"
s.close()
sys.exit(1)
data = int(data)
###If the data was -1, then the user did not exist and an error should be displayed. Otherwise ask for the
###Password and send it to the server.
if data != -1:
password = getpass.getpass("Enter your password please: ");
try:
s.sendto(password, ('127.0.0.1', PORT))
except:
print "There was a problem sending to the server"
s.close()
sys.exit(1)
else:
print "This first name was not recognised."
sys.exit(1)
###Again try to relieve data from the server and print out the output.
try:
data, address = s.recvfrom(MAX)
print data
s.close()
except:
print "There was a problem receiving to the server"
s.close()
sys.exit(1)
Client server code, the log does not work when called from the server while it is up.
I have tried reproducing the problem, but the script for the server did not execute. On my machine sys.argv[1:] returned [], so i modified this part of your script if sys.argv[1:] == ['server']: to if sys.argv[1:] == []:
Please see the response i got. You should look into that part. if sys.argv[1:] == ['server']:
The server is up with the ip 127.0.0.1
Server is up and listening at ('127.0.0.1', 1060)