Python获取当前公网ip并自动断开宽带连接实例代码
今天写了一个获取当前公网ip并且自动断开宽带连接的文件,和大家分享下。
这个文件的具体用途大家懂的,可以尽管拿去用,不过目前只适用于Windows平台,我的Python版本是2.7的,win32ras模块需要下载pywin32。
代码如下:
#!coding:cp936
importwin32ras
importtime,os
defConnect(dialname,account,passwd):
dial_params=(dialname,'','',account,passwd,'')
returnwin32ras.Dial(None,None,dial_params,None)
defDialBroadband():
dialname='宽带连接'#justaname
account='********'
passwd='****************'
try:
#handleisapid,fordisconnectorshowipadrress,ifconnectsuccessreturn0.
#accountistheusernamethatyourISPsupposed,passwdisthepassword.
handle,result=Connect(dialname,account,passwd)
ifresult==0:
print"Connectionsuccess!"
returnhandle,result
else:
print"Connectionfailed,waitfor5secondsandtryagain..."
time.sleep(5)
DialBroadband()
except:
print"Can'tfinishthisconnection,pleasecheckout."
return
defDisconnect(handle):
ifhandle!=None:
try:
win32ras.HangUp(handle)
print"Disconnectionsuccess!"
return"success"
except:
print"Disconnectionfailed,waitfor5secondsandtryagain..."
time.sleep(5)
Disconnect()
else:
print"Can'tfindtheprocess!"
return
defCheck_for_Broadband():
connections=[]
connections=win32ras.EnumConnections()
if(len(connections)==0):
print"Thesystemisnotrunninganybroadbandconnection."
return
else:
print"Thesystemisrunning%dbroadbandconnection."%len(connections)
returnconnections
defShowIpAddress(handle):
printwin32ras.GetConnectStatus(handle)
data=os.popen("ipconfig","r").readlines()
have_ppp=0
ip_str=None
forlineindata:
ifline.find("宽带连接")>=0:
have_ppp=1
#ifyoursystemlanguageisEnglish,youshouldwritelikethis:
#ifhave_pppandline.strip().startswith("IPAddress"):
#inothewords,replacethe"IPv4地址"to"IPAddress"
ifhave_pppandline.strip().startswith("IPv4地址"):
ip_str=line.split(":")[1].strip()
have_ppp=0
printip_str
#getmyipaddressanfdisconnectbroadbandconnection.
defmain():
data=Check_for_Broadband()
#ifexistrunningbroadbandconnection,disconnectedit.
ifdata!=None:
forpindata:
ShowIpAddress(p[0])
if(Disconnect(p[0])=="success"):
print"%shasbeendisconnected."%p[1]
time.sleep(3)
else:
pid,res=DialBroadband()
ShowIpAddress(pid)
time.sleep(3)
Disconnect(pid)
return"finshtest"
test=main()
printtest
基本的注释都有,大家可以自己参考。
总结
以上就是本文关于Python获取当前公网ip并自动断开宽带连接实例代码的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!