1. 程式人生 > >Python 之自動獲取公網IP

Python 之自動獲取公網IP

ras number success sel sql ror copy cnblogs 由於

Python 之自動獲取公網IP

2017年9月30日

0.預備知識

0.1 SQL基礎

ubuntuDebian系列安裝:

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

RedhatCentos 系列安裝:

1 [[email protected] ~]# yum install  mysql-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]:~/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 = rhttp://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中,讓它執行定時任務即可

Python 之自動獲取公網IP