Python 自动更新和发送IP地址
我在一台有ADSL连接的机器上运行SSH。我制作这个脚本是为了在机器每次有新的IP地址时给我发送一封电子邮件 我无法接近这台机器。我把脚本给了一个朋友,所以我无法执行调试来找出这个脚本的错误。我现在正在使用一个大学连接,它有一个静态ip地址。在上面运行脚本没有意义 因此,有没有关于如何改进/修复脚本的建议。有时我会收到无效的IP地址,有时IP地址会更改,但我没有收到电子邮件。我应该使用另一种方法来实现这种自动化吗Python 自动更新和发送IP地址,python,networking,automation,Python,Networking,Automation,我在一台有ADSL连接的机器上运行SSH。我制作这个脚本是为了在机器每次有新的IP地址时给我发送一封电子邮件 我无法接近这台机器。我把脚本给了一个朋友,所以我无法执行调试来找出这个脚本的错误。我现在正在使用一个大学连接,它有一个静态ip地址。在上面运行脚本没有意义 因此,有没有关于如何改进/修复脚本的建议。有时我会收到无效的IP地址,有时IP地址会更改,但我没有收到电子邮件。我应该使用另一种方法来实现这种自动化吗 import urllib import time import smtplib
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()
我建议您可能太频繁地访问服务器并被阻止
更改您的第一次
时间。sleep(5)
为时间。sleep(300)
感谢您的精彩脚本!这肯定会起作用(echoip.com作为urlopen数据)
可能更适合解决您的问题:注册一个dyndns(或类似)帐户并运行一个dyndns客户端守护程序……没错,没有一个ip.com免费提供相同的服务,但我觉得我可以使用python脚本来实现这一点,因为远程pc运行的是mac os
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()