Python 之自动获取公网IP

来源:转载

Python 之自动获取公网IP


2017年9月30日


0.预备知识

0.1 SQL 基础


ubuntu 、 Debian 系列安装 :



1 [email protected]:~/python-script#apt-get install mysql-server

Redhat 、 Centos 系列安装:



1 [[email protected] ~]# yum installmysql-server

登录数据库



1 [email protected]:~ $ 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 [email protected]:~/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 [email protected]:~/python-script#

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


Python MySQL insert 语句



1 [email protected]:~/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 [email protected]:~/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 [email protected]rypi:~/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 [email protected]:~/python-script#

savedb.py



1 [email protected]:~/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 [email protected]:~/python-script#

send_mail.py



1 [email protected]:~/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 <html>
16 <head>
17 <meta charset="utf-8" />
18 </head>
19 <body>
20 <em><h1>ip:%s</h1></em>
21 </body>
22 </html>
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 [email protected]:~/python-script#
39 print ("%s" %(line),end='')

3.效果


收到的邮件如下 :



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



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


分享给朋友:
您可能感兴趣的文章:
随机阅读: