I have SSH running on a machine with ADSL connection. I made this script to send me an email each time the machine has new a IP address.
The machine is not accessible by me. I gave the script to a friend so I cannot perform debugging to figure out what is wrong with this script. I'm using a university connection right now and it has a static ip address. There is no point running the script on it.
So any suggestions how to improve/fix the script. Sometimes I'll receive non valid IP addresses or sometimes the IP address will change but I don't get an email. Should I use another method for this kind of automation?
import urllib
import time
import smtplib
fromaddr = '***#gmail.com'
toaddrs = '***#gmail.com'
ip = ""
username = '****'
password = '****'
f = False
def update():
global ip,f
#print "sleeping 5 seconds"
time.sleep(5)
while not f:
try:
f = urllib.urlopen("http://automation.whatismyip.com/n09230945.asp")
except IOError, e:
print "no internet !"
time.sleep(5)
if not ip and f:
ip = f.read()
print "getting the first ip"
print ip
sendmail(ip)
print "mail sent"
else:
if f:
ip2 = f.read()
#print ip,ip2
if ip != ip2 and ip and ip2:
ip = ip2
print "new ip",ip,"sending mail"
sendmail(ip)
else:
print "ip is the same"
f = False
#print ip
def sendmail(ip):
a = False
while not a:
try:
#just to check if i have internet or not
a = urllib.urlopen("http://automation.whatismyip.com/n09230945.asp")
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.ehlo()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, ip)
server.quit()
except IOError, e:
print "no internet"
time.sleep(5)
#sendmail(ip)
print "program started"
while(1):
update()
I'd suggest that you might be hitting the server too often and getting blocked... http://forum.whatismyip.com/f14/pace-yourself-t6/
Change your first time.sleep(5) to time.sleep(300).
Thanks for great script! This will definitely work (with echoip.com as urlopen data)
import urllib
import time
import smtplib
fromaddr = '***'
toaddrs = '***'
ip = ""
username = '***'
password = '***'
f = False
def update():
global ip,f
#print "sleeping 5 seconds"
time.sleep(20)
while not f:
try:
f = urllib.urlopen("http://echoip.com")
except IOError as e:
print ("no internet !", e)
time.sleep(5)
if not ip and f:
ip = f.read()
print "getting the first ip"
print ip
sendmail(ip)
print "mail sent"
else:
if f:
ip2 = f.read()
#print ip,ip2
if ip != ip2 and ip and ip2:
ip = ip2
print "new ip",ip,"sending mail"
sendmail(ip)
else:
print "ip is the same"
f = False
#print ip
def sendmail(ip):
a = False
while not a:
try:
#just to check if i have internet or not
a = urllib.urlopen("http://echoip.com")
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.ehlo()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, ip)
server.quit()
except IOError as e:
print ("no internet", e)
time.sleep(10)
#sendmail(ip)
print "program started"
while(1):
update()
Related
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)
I created a HTTP proxy using this tutorial https://null-byte.wonderhowto.com/how-to/sploit-make-proxy-server-python-0161232/.
I am using this proxy with firefox browser. When I open a website in browser. The connection between firefox-proxy and proxy-webserver is successful and the proxy successfully receives data from webserver. But when I sent the data back to browser it doesn't render any page (I don't see webpage in browser). What may be the issue here ?
import socket, sys
from thread import *
try:
listening_port = int(raw_input("[*] Enter Listening Port Number: "))
except KeyboardInterrupt:
print "\n[*] User Requested An Interrupt"
print "[*] Application Exiting ..."
sys.exit()
max_conn = 20 #Max Connections in Queue
buffer_size = 262144 # Max socket Buffer size
def start():
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # initiates socket
s.bind(('', listening_port)) # Bind socket for listen
s.listen(max_conn) # start listening for incoming connections
print "[*] Initializing Sockets ... Done"
print "[*] Sockets Binded succesfully ..."
print("[*] Server started succesfully [ %d ]\n" % (listening_port))
except Exception, e:
print "[*] Unable to initialize socket", e
sys.exit(2)
while 1:
try:
conn, addr = s.accept() # Accept connection From client browser
print "Connection accepted from browser"
data = conn.recv(buffer_size) # Receive CLient Data
print "Received request from browser"
start_new_thread(conn_string, (conn, data, addr)) # start a thread
except KeyboardInterrupt:
print "\n[*] Proxy Server Shutting down ..."
sys.exit(1)
s.close()
def conn_string(conn, data, addr):
# Client Browser Request Appears Here
try:
first_line = data.split('\n')[0]
url = first_line.split(' ')[1]
print "URL ", url
http_pos = url.find("://") # find the position of ://
if (http_pos == -1):
temp = url
else:
temp = url[(http_pos+3):] # get the rest of the URL
print "http pos, Temp", http_pos, temp
port_pos = temp.find(":") # Find the postion of port (if any)
webserver_pos = temp.find("/") # Find the end of the web server
if webserver_pos == -1:
webserver_pos = len(temp)
webserver = ""
port = -1
#print "Port pos, webserver_pos", port_pos, webserver_pos
if (port_pos == -1 or webserver_pos < port_pos): # default port
port = 80
webserver = temp[:webserver_pos]
else:
# Specific port
port = int((temp[(port_pos+1):])[:webserver_pos-port_pos-1])
webserver = temp[:port_pos]
# print "WEB server", webserver
print "Data extracted from request Request"
proxy_server(webserver, port, conn, addr, data)
except Exception, e:
pass
def proxy_server(webserver, port, conn, addr, data):
try:
print "starting connection towebserver"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#print "connecing host", webserver, port
s.connect((webserver, port))
print "connected"
#print "data", data
s.send(data)
print "Request sent"
while 1:
# Read reply or data to from end web server
reply = s.recv(buffer_size)
print "Reply Received ", reply
if (len(reply) > 0):
conn.send(reply) # send reply back to client
# Send notification to proxy Server [script itself]
dar = float(len(reply))
dar = float(dar / 1024)
dar = "%.3s" % (str(dar))
dar = "%s KB" % (dar)
print "[*] Request Done: %s => %s <=" % (str(addr[0]), str(dar))
else:
break
s.close()
conn.close()
print "Conn CLosed ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
except socket.error, (value, message):
print "Error", message
s.close()
conn.close()
sys.exit(1)
start()
Where am I going wrong here. as far as i can tell this should work.
import socket, string
#some user data, change as per your taste
SERVER = 'irc.freenode.net'
PORT = 6667
NICKNAME = 'echoquote'
CHANNEL = '#python'
PASSWORD = 'nope'
import time
#open a socket to handle the connection
IRC = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#open a connection with the server
def irc_conn():
IRC.connect((SERVER, PORT))
#simple function to send data through the socket
def send_data(command):
IRC.send(command + '\n')
#join the channel
def join(channel):
send_data("JOIN %s" % channel)
#send login data (customizable)
def login(nickname, username='user', password = None, realname='Pythonist', hostname='Helena', servername='Server'):
send_data("USER %s %s %s %s" % (username, hostname, servername, realname))
send_data("NICK " + nickname)
send_data("nickserv identify %s %s\r\n" % (NICKNAME, PASSWORD))
time.sleep(3)
irc_conn()
login(NICKNAME)
join(CHANNEL)
while (1):
buffer = IRC.recv(1024)
msg = string.split(buffer)
message = ' '.join(msg[3:])
message = ''.join([x for x in message if x in string.printable])
if message:
print message + '\n'
if msg[0] == "PING": #check if server have sent ping command
send_data("PONG %s" % msg[1]) #answer with pong as per RFC 1459
if msg [1] == 'PRIVMSG' and msg[2] == NICKNAME:
filetxt = open('/tmp/msg.txt', 'a+') #open an arbitrary file to store the messages
nick_name = msg[0][:string.find(msg[0],"!")] #if a private message is sent to you catch it
message = ' '.join(msg[3:])
filetxt.write(string.lstrip(nick_name, ':') + ' -> ' + string.lstrip(message, ':') + '\n') #write to the file
filetxt.flush() #don't wait for next message, write it now!
send_data("nickserv identify %s %s\r\n" % (NICKNAME, PASSWORD))
There is no nickserv command in IRC. This is an alias in some IRC clients, and all it does is send a private message to NickServ. Read the IRC specification, and stop reinventing wheels — use an existing IRC library, eg. twisted.words, or an existing IRC bot solution.
I entered http://127.0.0.1:443/www.google.com and I got 'Illegal request' on the command prompt.
It doesn't work from connecting to port 80 in that code.
what is wrong and How can I get this web site using proxy server?
(I already set proxy setting of internet browser-127.0.0.1 (ip), 443(port)
` Hello.py
from socket import *
import sys
from idlelib.rpc import response_queue
if len(sys.argv) <= 1:
print ('Usage : "python ProxyServer.py server_ip"\n [server_ip : It is the IP Address Of Proxy Server')
sys.exit(2)
# Create a server socket, bind it to a port and start listening
tcpSerSock = socket(AF_INET, SOCK_STREAM)
port = 443
max_connections = 2
tcpSerSock = socket(AF_INET, SOCK_STREAM)
tcpSerSock.bind((sys.argv[1],port))
tcpSerSock.listen(max_connections)
while 1:
# Start receiving data from the client
print ('Ready to serve...')
tcpCliSock, addr = tcpSerSock.accept()
print ('Received a connection from:', addr)
message = tcpCliSock.recv(1024)
print ('Msg: ' ,message)
# Extract the filename from the given message
print ('Msg decoded: ', message.decode().split()[1])
filename = message.decode().split()[1].partition("/")[2]
print ('File name: ', filename)
fileExist = "false"
filetouse = "/" + filename
print ('File touse: ', filetouse)
try:
# Check whether the file exist in the cache
f = open(filetouse[1:], "r")
outputdata = f.readlines()
fileExist = "true"
print ('File exists')
# ProxyServer finds a cache hit and generates a response message
tcpCliSock.send("HTTP/1.0 200 OK\r\n")
tcpCliSock.send("Content-Type:text/html\r\n")
resp = ""
for s in outputdata:
resp += s
tcpCliSock.send(resp)
print ('Read from cache')
# Error handling for file not found in cache
except IOError:
if fileExist == "false":
# Create a socket on the proxy server
c = socket(AF_INET, SOCK_STREAM)
hostn = filename.replace("www.","",1)
print ('File doesn\'t exist')
print (hostn)
try:
# Connect to the socket to port 80
c.connect((hostn, 80))
# Create a temporary file on this socket and ask port 80
# for the file requested by the client
fileobj = c.makefile('r', 0)
fileobj.write("GET " + "http://" + filename + " HTTP/1.0\n\n")
# Read the response into buffer
resp = c.recv(4096)
response = ""
while resp:
response += resp
resp = c.recv(4096)
# Create a new file in the cache for the requested file.
# Also send the response in the buffer to client socket and the corresponding file in the cache
tmpFile = open("./" + filename,"w")
tmpFile.write(response)
tmpFile.close()
tcpCliSock.close()
except:
print ("Illegal request")
else:
# HTTP response message for file not found
pass
# Close the client and the server sockets
tcpCliSock.close()`
Is this an valid example from Python's smtplib? How, from this example, would one send email without giving the password?
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()
You can send emails without using a password assuming the server configuration allow that.