Python中關於自動取得公網IP的實例講解
下面小編就為大家帶來一篇Python之自動取得公網IP的實例講解。小編覺得蠻不錯的,現在就分享給大家,也給大家做個參考。一起跟著小編過來看看吧
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 id is 36 Server version: 10.0.30-MariaDB-0+deb8u2 (Raspbian) Copyright (c) 2000, 2016, 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` bigint(20) NOT NULL AUTO_INCREMENT, `time` datetime DEFAULT NULL, `old_data` varchar(50) DEFAULT NULL, `new_data` varchar(50) DEFAULT NULL, PRIMARY KEY (`serial_number`) ) ENGINE=InnoDB AUTO_INCREMENT=3 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
安裝:
安装: 解压 unzip MySQL-python-1.2.5.zip 进入解压后目录 cd MySQL-python-1.2.5/ 安装依赖 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.pyroot@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#
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#
#
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,'25') 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.效果
收到的郵件如下:以上是Python中關於自動取得公網IP的實例講解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

PHP主要是過程式編程,但也支持面向對象編程(OOP);Python支持多種範式,包括OOP、函數式和過程式編程。 PHP適合web開發,Python適用於多種應用,如數據分析和機器學習。

PHP適合網頁開發和快速原型開發,Python適用於數據科學和機器學習。 1.PHP用於動態網頁開發,語法簡單,適合快速開發。 2.Python語法簡潔,適用於多領域,庫生態系統強大。

PHP起源於1994年,由RasmusLerdorf開發,最初用於跟踪網站訪問者,逐漸演變為服務器端腳本語言,廣泛應用於網頁開發。 Python由GuidovanRossum於1980年代末開發,1991年首次發布,強調代碼可讀性和簡潔性,適用於科學計算、數據分析等領域。

Python更適合初學者,學習曲線平緩,語法簡潔;JavaScript適合前端開發,學習曲線較陡,語法靈活。 1.Python語法直觀,適用於數據科學和後端開發。 2.JavaScript靈活,廣泛用於前端和服務器端編程。

在 Sublime Text 中運行 Python 代碼,需先安裝 Python 插件,再創建 .py 文件並編寫代碼,最後按 Ctrl B 運行代碼,輸出會在控制台中顯示。

在 Visual Studio Code(VSCode)中編寫代碼簡單易行,只需安裝 VSCode、創建項目、選擇語言、創建文件、編寫代碼、保存並運行即可。 VSCode 的優點包括跨平台、免費開源、強大功能、擴展豐富,以及輕量快速。

VS Code 可用於編寫 Python,並提供許多功能,使其成為開發 Python 應用程序的理想工具。它允許用戶:安裝 Python 擴展,以獲得代碼補全、語法高亮和調試等功能。使用調試器逐步跟踪代碼,查找和修復錯誤。集成 Git,進行版本控制。使用代碼格式化工具,保持代碼一致性。使用 Linting 工具,提前發現潛在問題。

在 Notepad 中運行 Python 代碼需要安裝 Python 可執行文件和 NppExec 插件。安裝 Python 並為其添加 PATH 後,在 NppExec 插件中配置命令為“python”、參數為“{CURRENT_DIRECTORY}{FILE_NAME}”,即可在 Notepad 中通過快捷鍵“F6”運行 Python 代碼。
