Py学习  »  Python

Python 之自动获取公网IP

python • 6 年前 • 708 次点击  

0.预备知识

0.1 SQL基础

ubuntuDebian系列安装:

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

RedhatCentos 系列安装:

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

登录数据库

1 pi@raspberrypi:~ $ mysql -uroot -p -hlocalhost 
2
Enter password: 3 Welcome to the MariaDB monitor.  Commands end with ; or \g.
4
Your MariaDB connection id is 36
5
Server version: 10.0.30-MariaDB-0+deb8u2 (Raspbian)
6

7
Copyright (c) 2000, 2016, Oracle, MariaDB Corporation Ab and others.
8

9
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
10
11 MariaDB [(none)]>

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

创建数据库、创建数据表

创建数据库语法如下

1 MariaDB [(none)]> help create database 
2
Name: 'CREATE DATABASE'
3
Description:
4
Syntax:
5
CREATE {DATABASE | SCHEMA} [IF NOT EXISTS] db_name
6
   [create_specification] ...
7

8
create_specification:
9
[DEFAULT] CHARACTER SET [=] charset_name
10 | [DEFAULT] COLLATE [=] collation_name
11
12 CREATE DATABASE creates a database with the given name. To use this
13 statement, you need the CREATE privilege for the database. CREATE
14 SCHEMA is a synonym for CREATE DATABASE.
15
16 URL: https://mariadb.com/kb/en/create-database/
17
18
19 MariaDB [(none)]>

创建数据表语法如下

1 MariaDB [(none)]> help create table 
2
Name: 'CREATE TABLE'
3
Description:
4
Syntax:
5
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
6
   (create_definition,...)
7
   [table_options]
8
   [partition_options]
9

10 Or:
11
12 CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
13    [(create_definition,...)]
14    [table_options]
15    [partition_options]
16 select_statement

创建数据库ServiceLogs

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

创建数据

1 MariaDB [(none)]> CREATE TABLE `python_ip_logs` (
2 `serial_number` bigint(20) NOT NULL AUTO_INCREMENT,
3 `time` datetime DEFAULT NULL,
4 `old_data` varchar(50) DEFAULT NULL,
5 `new_data` varchar(50) DEFAULT NULL,
6 PRIMARY KEY (`serial_number`)
7 ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1

表内容的查

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

0.2 python连接操作MySQL

模块下载安装

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

安装:

1 安装: 
2
解压
3
unzip MySQL-python-1.2.5.zip
4
进入解压后目录
5
cd MySQL-python-1.2.5/
6
安装依赖
7
apt-get install libmysqlclient-dev
8
安装
9
python setup.py install
10 如果为0则安装OK
11 echo $?

连接Mysql

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

4
import MySQLdb
5

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

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

Python MySQL insert语句

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

4
import MySQLdb
5

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

8
cursor = db.cursor()
9

10 sql = "insert INTO python_ip_logs VALUES (DEFAULT,'2017-09-29 22:46:00','123','456')"
11
12 cursor.execute(sql)
13 db.commit()
14
15 db.close()
16 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

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

5
import requests
6
import send_mail
7
import savedb
8

9
def get_out_ip() :
10 url = r'http://www.trackip.net/'
11 r = requests.get(url)
12 txt = r.text
13 ip = txt[txt.find('title')+6:txt.find('/title')-1]
14 return (ip)
15
16 def main() :
17 try:
18                savedb.general_files()
19
20 tip = get_out_ip()
21 cip = savedb.read_files()
22
23
24 if savedb.write_files(cip,tip) :
25                        send_mail.SamMail(get_out_ip())
26 except :
27 return False
28
29 if __name__=="__main__" :
30        main()
31 root@raspberrypi:~/python-script#

savedb.py

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

4
import MySQLdb
5
import os
6
import time
7

8
dirname = "logs"
9
filename = "logs/.ip_tmp"
10
11 def general_files(Default_String="Null") :
12
13 var1 = Default_String
14
15 if not os.path.exists(dirname) :
16                os.makedirs(dirname)
17
18 if not os.path.exists(filename) :
19 f = open(filename,'w')
20                f.write(var1)
21                f.close()
22
23 def read_files() :
24 f = open(filename,'r')
25 txt = f.readline()
26 return (txt)
27
28 def write_files(txt,new_ip) :
29 if not txt == new_ip :
30 NowTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
31 old_ip = read_files()
32                os.remove(filename)
33                general_files(new_ip)
34                write_db(NowTime,old_ip,new_ip)
35 return True
36 else:
37 return False
38
39
40 def write_db(NowTime,Old_ip,New_ip) :
41 db = MySQLdb.connect("主机","用户名","密码","库名")
42
43 cursor = db.cursor()
44
45 sql = """
46                INSERT INTO python_ip_logs 47                VALUES
48                (DEFAULT,"%s","%s","%s")
49 """ %(NowTime,Old_ip,New_ip)
50
51 try:
52                cursor.execute(sql)
53                db.commit()
54 except:
55                db.rollback()              
56
57        db.close()
58 root@raspberrypi:~/python-script#

send_mail.py

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

4
import smtplib
5
import email.mime.text
6

7
def SamMail(HtmlString) :
8
HOST = "smtp.163.com "
9
SUBJECT = "主题"
10 TO = "对方的邮箱地址"
11 FROM = "来自于哪里"
12 Remask = "The IP address has been changed"
13
14 msg = email.mime.text.MIMEText("""
15        
16                
17                        
18                
19                
20                        

ip:%s


21                
22        
23 """ %(HtmlString),"html","utf-8")
24
25 msg['Subject'] = SUBJECT
26 msg['From'] = FROM
27 msg['TO'] = TO
28
29 try:
30 server = smtplib.SMTP()
31 server.connect(HOST,'25')
32        server.starttls()
33 server.login("用户名","密码")
34        server.sendmail(FROM,TO,msg.as_string())
35        server.quit()
36 except:
37 print ("Send mail Error")
38 root@raspberrypi:~/python-script#
39 print ("%s" %(line),end='')

3.效果

收到的邮件如下:

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

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

作者:王李
源自:
http://www.cnblogs.com/wang-li/p/7615118.html
声明: 文章著作权归作者所有,如有侵权,请联系小编删除。

 关注+转发 
感谢大家


今天看啥 - 高品质阅读平台
本文地址:http://www.jintiankansha.me/t/6glxq0ubFH
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/3698
 
708 次点击