Python實現的線上保持
偶所在的校園網,如果一段時間沒有下載流量則自動斷網,所以編寫此程式定期訪問網路,下載一些無關緊要的資料,來保持網路連結。
# -*- coding: gbk -*-
from socket import *
import time
GET_DATA="""/
GET / HTTP/1.1
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-shockwave-flash, */*
Accept-Language: zh-cn
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; Maxthon)
Host: %s
Connection: Keep-Alive
"""
siteList=[
('202.108.22.5',80),
('61.135.133.103',80),
('71.5.7.138',80),
('216.109.112.135',80),
('202.108.9.16',80)
]
def loop():
global siteList
for addr,port in siteList:
data=''
try:
s=socket(AF_INET,SOCK_STREAM)
s.settimeout(30) #逾時30秒
s.connect((addr,port))
s.send(GET_DATA%addr)
data=s.recv(64)
if data=='':
print 'IP: %s'%addr+" can't connect!"
else:
print 'IP: %s'%addr+" OK !!!!!!!!!!!!!!!!"
except timeout,detail:
#逾時錯誤
print "逾時錯誤 %s"%addr
pass
except error,detail:
#其他Socket錯誤
print "其他Socket錯誤 %s"%addr
pass
#except:
#所有錯誤
# pass
s.close()
print '='*60
time.sleep(30)
return
def main():
while True:
loop()
return
if __name__=='__main__':
main()