Python 之自动获取公网IP

2017年9月30日

文档下载:https://wenku.baidu.com/view/ff40aef7f021dd36a32d7375a417866fb84ac0fd

0.预备知识

0.1 SQL基础

ubuntu、Debian系列安装:

 root@raspberrypi:~/python-script#  apt-get install mysql-server 

Redhat、Centos 系列安装:

 [root@localhost ~]# yum install  mysql-server

登录数据库

 pi@raspberrypi:~ $ mysql -uroot -p -hlocalhost
 Enter password:
 Welcome to the MariaDB monitor.  Commands end with ; or \g.
 Your MariaDB connection
 Server version: -MariaDB-+deb8u2 (Raspbian)

 Copyright (c) , , Oracle, MariaDB Corporation Ab and others.

 Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

 MariaDB [(none)]> 

其中,mysql是客户端命令 -u是指定用户 -p是密码 -h是主机

创建数据库、创建数据表

创建数据库语法如下

 MariaDB [(none)]> help create database
 Name: 'CREATE DATABASE'
 Description:
 Syntax:
 CREATE {DATABASE | SCHEMA} [IF NOT EXISTS] db_name
     [create_specification] ...

 create_specification:
     [DEFAULT] CHARACTER SET [=] charset_name
   | [DEFAULT] COLLATE [=] collation_name

 CREATE DATABASE creates a database with the given name. To use this
 statement, you need the CREATE privilege for the database. CREATE
 SCHEMA is a synonym for CREATE DATABASE.

 URL: https://mariadb.com/kb/en/create-database/

 MariaDB [(none)]> 

创建数据表语法如下

 MariaDB [(none)]> help create table
 Name: 'CREATE TABLE'
 Description:
 Syntax:
 CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
     (create_definition,...)
     [table_options]
     [partition_options]

 Or:

 CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
     [(create_definition,...)]
     [table_options]
     [partition_options]
     select_statement

创建数据库ServiceLogs

 MariaDB [(none)]> CREATE DATABASE `ServiceLogs`

创建数据表

 MariaDB [(none)]> CREATE TABLE `python_ip_logs` (
   `serial_number` ) NOT NULL AUTO_INCREMENT,
   `time` datetime DEFAULT NULL,
   `old_data` ) DEFAULT NULL,
   `new_data` ) DEFAULT NULL,
   PRIMARY KEY (`serial_number`)
 ) ENGINE DEFAULT CHARSET=latin1 

表内容的查询

 MariaDB [ServiceLogs]> select * from python_ip_logs;
 Empty set (0.00 sec)

0.2 python连接操作MySQL

模块下载安装

下载路径: https://pypi.python.org/pypi/MySQL-python

安装:

 安装:
 解压
 .zip
 进入解压后目录
 cd MySQL-python-/
 安装依赖
 apt-get install libmysqlclient-dev
 安装
 python setup.py install
 如果为0则安装OK
 echo $?

连接Mysql

 root@raspberrypi:~/python-script# cat p_mysql_3.py
 #!/usr/bin/env python

 import MySQLdb

 try :
         conn = MySQLdb.connect("主机","用户名","密码","ServiceLogs")
         print ("Connect Mysql successful")
 except:
         print ("Connect MySQL Fail")
 root@raspberrypi:~/python-script# 

如果输出Connect Mysql successful则说明连接OK

Python MySQL insert语句

 root@raspberrypi:~/python-script# cat p_mysql1.py
 #!/usr/bin/env python

 import MySQLdb

 db = MySQLdb.connect("localhost","root","root","ServiceLogs")

 cursor = db.cursor()

 sql = "insert INTO python_ip_logs VALUES (DEFAULT,'2017-09-29 22:46:00','123','456')"

 cursor.execute(sql)
 db.commit()

 db.close()
 root@raspberrypi:~/python-script# 

执行完成后可以mysql客户端SELECT语句查看结果

1.需求

1.1 需求

由于宽带每次重启都会重新获得一个新的IP,那么在这种状态下,在进行ssh连接的时候会出现诸多的不便,好在之前还有花生壳软件,它能够通过域名来找到你的IP地址,进行访问,这样是最好的,不过最近花生壳也要进行实名认证才能够使用,于是乎,这就催发了我写一个python脚本来获取公网IP的冲动。

实现效果:当IP变更时,能够通过邮件进行通知,且在数据库中写入数据

1.2 大致思路

1.3 流程图

其他代码均没有什么好画的

2.代码编写

2.1.1 编写python代码

getnetworkip.py

 root@raspberrypi:~/python-script# cat getnetworkip.py
 #!/usr/bin/env python
 # coding:UTF-8

 import requests
 import send_mail
 import savedb

 def get_out_ip() :
         url = r'http://www.trackip.net/'
         r = requests.get(url)
         txt = r.text
         ip = txt[txt.find('title')+6:txt.find('/title')-1]
         return (ip)

 def main() :
         try:
                 savedb.general_files()

                 tip = get_out_ip()
                 cip = savedb.read_files()

                 if savedb.write_files(cip,tip) :
                         send_mail.SamMail(get_out_ip())
         except :
                 return False

 if __name__=="__main__" :
         main()
 root@raspberrypi:~/python-script# 

savedb.py

 root@raspberrypi:~/python-script# cat savedb.py
 #!/usr/bin/env python

 import MySQLdb
 import os
 import time

 dirname = "logs"
 filename = "logs/.ip_tmp"

 def general_files(Default_String="Null") :

         var1 = Default_String

         if not os.path.exists(dirname) :
                 os.makedirs(dirname)

         if not os.path.exists(filename) :
                 f = open(filename,'w')
                 f.write(var1)
                 f.close()

 def read_files() :
         f = open(filename,'r')
         txt = f.readline()
         return (txt)

 def write_files(txt,new_ip) :
         if not txt == 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)
                 return True
         else:
                 return False

 def write_db(NowTime,Old_ip,New_ip) :
         db = MySQLdb.connect("主机","用户名","密码","库名")

         cursor = db.cursor()

         sql = """
                 INSERT INTO python_ip_logs
                 VALUES
                 (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.py

 root@raspberrypi:~/python-script# cat send_mail.py
 #!/usr/bin/env python

 import smtplib
 import email.mime.text

 def SamMail(HtmlString) :
     HOST = "smtp.163.com"
     SUBJECT = "主题"
     TO = "对方的邮箱地址"
     FROM = "来自于哪里"
     Remask = "The IP address has been changed"

     msg = email.mime.text.MIMEText("""
         <html>
                 <head>
                         <meta charset="utf-8" />
                 </head>
                 <body>
                         <em><h1>ip:%s</h1></em>
                 </body>
         </html>
         """ %(HtmlString),"html","utf-8")

     msg['Subject'] = SUBJECT
     msg['From'] = FROM
     msg['TO'] = TO

     try:
         server = smtplib.SMTP()
         server.connect(HOST,')
         server.starttls()
         server.login("用户名","密码")
         server.sendmail(FROM,TO,msg.as_string())
         server.quit()
     except:
         print ("Send mail Error")
 root@raspberrypi:~/python-script#
     print ("%s" %(line),end='')

3.效果

收到的邮件如下:

利用SELECT查看表,效果如下:

把脚本放入crontab中,让它执行定时任务即可

Python 之自动获取公网IP的更多相关文章

  1. python编写的自动获取代理IP列表的爬虫-chinaboywg-ChinaUnix博客

    python编写的自动获取代理IP列表的爬虫-chinaboywg-ChinaUnix博客 undefined Python多线程抓取代理服务器 | Linux运维笔记 undefined java如 ...

  2. python获取公网ip,本地ip及所在国家城市等相关信息收藏

    python获取公网ip的几种方式       from urllib2 import urlopen   my_ip = urlopen('http://ip.42.pl/raw').read() ...

  3. python获取公网ip的几种方式

    python获取公网ip的几种方式 转 https://blog.csdn.net/conquerwave/article/details/77666226 from urllib2 import u ...

  4. C#联机获取公网IP

    C#获取IP的方式有很多种,这里通过http://www.ipip.net/这个稳定的在线IP库的来获取公网IP. string tempip = "0.0.0.0"; WebRe ...

  5. Delphi获取公网IP地址函数

    uses IdHTTP; function GetPublicIP: string; var strIP, URL: string; iStart, iEnd: Integer; MyIdHTTP: ...

  6. 获取本地ip和获取公网ip

    import socket def get_local_ip(): ''' 获取本地ip地址 :return: ''' s = socket.socket(socket.AF_INET, socket ...

  7. Linux:自动获取静态IP地址,清空iptable,修改selinux脚本

    自动获取静态IP地址,清空iptable,修改selinux脚本 环境:VMware 平台:centos6.8全新 功能: 1)应用ifconfig -a,route -n,cat /etc/reso ...

  8. 解决:win8.1 oepnvpn客户端 redirect-gateway def1无效,自动获取的IP没有网关问题

    解决:win8.1 oepnvpn客户端 redirect-gateway def1无效,自动获取的IP没有网关问题 该问题是操作系统权限问题,需要将程序设置为以管理员模式运行和以windows7兼容 ...

  9. 通过AWS的DHCP自动获取的IP地址是否会发生改变?

    针对您的问题,分析如下:1.在一个VPC内,通过AWS的DHCP自动获取的IP地址,在如何情况下会发生改变?例如我把vpc的内所有100个ec2实例全部关闭,再全部重新打开,是否会发生IP地址变化的情 ...

随机推荐

  1. 在BCH硬分叉后防止重放攻击-1

    导致新加密货币的硬分叉为加密交换运营商带来了独特的机遇和挑战.Poloniex在最近的Bitcoin Cash硬叉之后面临的一个挑战是保护我们的客户免受重播攻击.由于SV链后面的开发团队选择在分叉后近 ...

  2. 安装git工具在ubuntu系统

    Git is one of the most popular tools used for distributed version control system(VCS). Git is common ...

  3. laravel 门面的介绍和使用

    #上文讲述了laravel中怎么用容器依赖注入类的示例.其实在服务提供者上面在封装一层静态调用,这就是门面.静态调用门面,返回了容器中注册的别名和实例. #下面是测试的示例 #先创建要操作的类 < ...

  4. linux 使用笔记1

    Zox's code life 人生就是不停的战斗! xxx is not in the sudoers file.This incident will be reported.的解决方法 1.切换到 ...

  5. windows下Git的使用教程(github)

    这表文章主要是用命令操作: 使用可视化软件操作:https://www.cnblogs.com/mswyf/p/9261859.html 一.下载安装Git Bash 下载安装:https://www ...

  6. 20172306 《Java程序设计》第二周学习总结

    20172306<Java程序设计>第二周学习总结 教材学习内容总结 这一周的学习,我觉得我比上一周认真多了,而且我突然发现慢慢学习的过程中,以前有一些多余自己打出来的东西,有了更清晰的认 ...

  7. How to Set Ckeditor ReadOnly Mode

    CKEditor API makes it possible to render the editor content read-only (and thus impossible for the u ...

  8. Python之socket编程进阶版

    1.socket之简单的ssh功能 2.socket之简单的ftp服务器 3.socketserver的用法 4.socketserver的多并发的实现 1.socket实现ssh服务 1.1我们现在 ...

  9. maven3 学习

    主要参考博文:http://www.cnblogs.com/yjmyzz/p/3495762.html 修正: 1.下载maven 3.1.1 先到官网http://maven.apache.org/ ...

  10. [转]11种常见sqlmap使用方法详解

    sqlmap也是渗透中常用的一个注入工具,其实在注入工具方面,一个sqlmap就足够用了,只要你用的熟,秒杀各种工具,只是一个便捷性问题,sql注入另一方面就是手工党了,这个就另当别论了.今天把我一直 ...