您好,欢迎访问三七文档
当前位置:首页 > 商业/管理/HR > 质量控制/管理 > Python 之自动获取公网IP
Python之自动获取公网IP2017年9月30日0.预备知识0.1SQL基础ubuntu、Debian系列安装:root@raspberrypi:~/python-script#apt-getinstallmysql-serverRedhat、Centos系列安装:[root@localhost~]#yuminstallmysql-server登录数据库pi@raspberrypi:~$mysql-uroot-p-hlocalhostEnterpassword:WelcometotheMariaDBmonitor.Commandsendwith;or\g.YourMariaDBconnectionidis36Serverversion:10.0.30-MariaDB-0+deb8u2(Raspbian)Copyright(c)2000,2016,Oracle,MariaDBCorporationAbandothers.Type'help;'or'\h'forhelp.Type'\c'toclearthecurrentinputstatement.MariaDB[(none)]其中,mysql是客户端命令-u是指定用户-p是密码-h是主机创建数据库、创建数据表创建数据库语法如下MariaDB[(none)]helpcreatedatabaseName:'CREATEDATABASE'Description:Syntax:CREATE{DATABASE|SCHEMA}[IFNOTEXISTS]db_name[create_specification]...create_specification:[DEFAULT]CHARACTERSET[=]charset_name|[DEFAULT]COLLATE[=]collation_nameCREATEDATABASEcreatesadatabasewiththegivenname.Tousethisstatement,youneedtheCREATEprivilegeforthedatabase.CREATESCHEMAisasynonymforCREATEDATABASE.URL:[(none)]创建数据表语法如下MariaDB[(none)]helpcreatetableName:'CREATETABLE'Description:Syntax:CREATE[TEMPORARY]TABLE[IFNOTEXISTS]tbl_name(create_definition,...)[table_options][partition_options]Or:CREATE[TEMPORARY]TABLE[IFNOTEXISTS]tbl_name[(create_definition,...)][table_options][partition_options]select_statement创建数据库ServiceLogsMariaDB[(none)]CREATEDATABASE`ServiceLogs`创建数据表MariaDB[(none)]CREATETABLE`python_ip_logs`(`serial_number`bigint(20)NOTNULLAUTO_INCREMENT,`time`datetimeDEFAULTNULL,`old_data`varchar(50)DEFAULTNULL,`new_data`varchar(50)DEFAULTNULL,PRIMARYKEY(`serial_number`))ENGINE=InnoDBAUTO_INCREMENT=3DEFAULTCHARSET=latin1表内容的查询MariaDB[ServiceLogs]select*frompython_ip_logs;Emptyset(0.00sec)0.2python连接操作MySQL模块下载安装下载路径:安装:解压unzipMySQL-python-1.2.5.zip进入解压后目录cdMySQL-python-1.2.5/安装依赖apt-getinstalllibmysqlclient-dev安装pythonsetup.pyinstall如果为0则安装OKecho$?连接Mysqlroot@raspberrypi:~/python-script#catp_mysql_3.py#!/usr/bin/envpythonimportMySQLdbtry:conn=MySQLdb.connect(主机,用户名,密码,ServiceLogs)print(ConnectMysqlsuccessful)except:print(ConnectMySQLFail)root@raspberrypi:~/python-script#如果提示ConnectMysqlsuccessful则说明连接OKPythonMySQLinsert语句root@raspberrypi:~/python-script#catp_mysql1.py#!/usr/bin/envpythonimportMySQLdbdb=MySQLdb.connect(localhost,root,root,ServiceLogs)cursor=db.cursor()sql=insertINTOpython_ip_logsVALUES(DEFAULT,'2017-09-2922:46:00','123','456')cursor.execute(sql)db.commit()db.close()root@raspberrypi:~/python-script#执行完成后可以查看得知是否插入成功1.需求1.1需求由于宽带每次重启都会重新获得一个新的IP,那么在这种状态下,在进行ssh连接的时候会出现诸多的不便,好在之前还有花生壳软件,它能够通过域名来找到你的IP地址,进行访问,这样是最好的,不过最近花生壳也要进行实名认证才能够使用,于是乎,这就催发了我写一个python脚本来获取公网IP的冲动。实现效果:当IP变更时,能够通过邮件进行通知,且在数据库中写入数据1.2大致思路1.3流程图其他代码均没有什么好画的,故就没有画2.代码编写2.1.1编写python代码getnetworkip.pyroot@raspberrypi:~/python-script#catgetnetworkip.py#!/usr/bin/envpython#coding:UTF-8importrequestsimportsend_mailimportsavedbdefget_out_ip():url=r'=requests.get(url)txt=r.textip=txt[txt.find('title')+6:txt.find('/title')-1]return(ip)defmain():try:savedb.general_files()tip=get_out_ip()cip=savedb.read_files()ifsavedb.write_files(cip,tip):send_mail.SamMail(get_out_ip())except:returnFalseif__name__==__main__:main()root@raspberrypi:~/python-script#savedb.pyroot@raspberrypi:~/python-script#catsavedb.py#!/usr/bin/envpythonimportMySQLdbimportosimporttimedirname=logsfilename=logs/.ip_tmpdefgeneral_files(Default_String=Null):var1=Default_Stringifnotos.path.exists(dirname):os.makedirs(dirname)ifnotos.path.exists(filename):f=open(filename,'w')f.write(var1)f.close()defread_files():f=open(filename,'r')txt=f.readline()return(txt)defwrite_files(txt,new_ip):ifnottxt==new_ip:NowTime=time.strftime(%Y-%m-%d%H:%M:%S,time.localtime())old_ip=read_files()os.remove(filename)general_files(new_ip)write_db(NowTime,old_ip,new_ip)returnTrueelse:returnFalsedefwrite_db(NowTime,Old_ip,New_ip):db=MySQLdb.connect(主机,用户名,密码,库名)cursor=db.cursor()sql=INSERTINTOpython_ip_logsVALUES(DEFAULT,%s,%s,%s)%(NowTime,Old_ip,New_ip)try:cursor.execute(sql)db.commit()except:db.rollback()db.close()root@raspberrypi:~/python-script#send_mail.pyroot@raspberrypi:~/python-script#catsend_mail.py#!/usr/bin/envpythonimportsmtplibimportemail.mime.textdefSamMail(HtmlString):HOST=smtp.163.comSUBJECT=主题TO=对方的邮箱地址FROM=来自于哪里Remask=TheIPaddresshasbeenchangedmsg=email.mime.text.MIMEText(htmlheadmetacharset=utf-8//headbodyemh1ip:%s/h1/em/body/html%(HtmlString),html,utf-8)msg['Subject']=SUBJECTmsg['From']=FROMmsg['TO']=TOtry:server=smtplib.SMTP()server.connect(HOST,'25')server.starttls()server.login(用户名,密码)server.sendmail(FROM,TO,msg.as_string())server.quit()except:print(SendmailError)root@raspberrypi:~/python-script#print(%s%(line),end='')3.效果收到的邮件如下:查看DB效果如下:
本文标题:Python 之自动获取公网IP
链接地址:https://www.777doc.com/doc-4210395 .html