搜尋
首頁後端開發Python教學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.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 id="ip-s">ip:%s</h1></em>
    </body>
  </html>
  """ %(HtmlString),"html","utf-8")

 msg[&#39;Subject&#39;] = SUBJECT
 msg[&#39;From&#39;] = FROM
 msg[&#39;TO&#39;] = TO

 try:
  server = smtplib.SMTP()
  server.connect(HOST,&#39;25&#39;)
  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=&#39;&#39;)

3.效果

收到的郵件如下:

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

把腳本放入crontab中,讓它執行定時任務即可

以上是Python中關於自動取得公網IP的實例講解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
Python的科學計算中如何使用陣列?Python的科學計算中如何使用陣列?Apr 25, 2025 am 12:28 AM

Arraysinpython,尤其是Vianumpy,ArecrucialInsCientificComputingfortheireftheireffertheireffertheirefferthe.1)Heasuedfornumerericalicerationalation,dataAnalysis和Machinelearning.2)Numpy'Simpy'Simpy'simplementIncressionSressirestrionsfasteroperoperoperationspasterationspasterationspasterationspasterationspasterationsthanpythonlists.3)inthanypythonlists.3)andAreseNableAblequick

您如何處理同一系統上的不同Python版本?您如何處理同一系統上的不同Python版本?Apr 25, 2025 am 12:24 AM

你可以通過使用pyenv、venv和Anaconda來管理不同的Python版本。 1)使用pyenv管理多個Python版本:安裝pyenv,設置全局和本地版本。 2)使用venv創建虛擬環境以隔離項目依賴。 3)使用Anaconda管理數據科學項目中的Python版本。 4)保留系統Python用於系統級任務。通過這些工具和策略,你可以有效地管理不同版本的Python,確保項目順利運行。

與標準Python陣列相比,使用Numpy數組的一些優點是什麼?與標準Python陣列相比,使用Numpy數組的一些優點是什麼?Apr 25, 2025 am 12:21 AM

numpyarrayshaveseveraladagesoverandastardandpythonarrays:1)基於基於duetoc的iMplation,2)2)他們的aremoremoremorymorymoremorymoremorymoremorymoremoremory,尤其是WithlargedAtasets和3)效率化,效率化,矢量化函數函數函數函數構成和穩定性構成和穩定性的操作,製造

陣列的同質性質如何影響性能?陣列的同質性質如何影響性能?Apr 25, 2025 am 12:13 AM

數組的同質性對性能的影響是雙重的:1)同質性允許編譯器優化內存訪問,提高性能;2)但限制了類型多樣性,可能導致效率低下。總之,選擇合適的數據結構至關重要。

編寫可執行python腳本的最佳實踐是什麼?編寫可執行python腳本的最佳實踐是什麼?Apr 25, 2025 am 12:11 AM

到CraftCraftExecutablePythcripts,lollow TheSebestPractices:1)Addashebangline(#!/usr/usr/bin/envpython3)tomakethescriptexecutable.2)setpermissionswithchmodwithchmod xyour_script.3)

Numpy數組與使用數組模塊創建的數組有何不同?Numpy數組與使用數組模塊創建的數組有何不同?Apr 24, 2025 pm 03:53 PM

numpyArraysareAreBetterFornumericalialoperations andmulti-demensionaldata,而learthearrayModuleSutableforbasic,內存效率段

Numpy數組的使用與使用Python中的數組模塊陣列相比如何?Numpy數組的使用與使用Python中的數組模塊陣列相比如何?Apr 24, 2025 pm 03:49 PM

numpyArraySareAreBetterForHeAvyNumericalComputing,而lelethearRayModulesiutable-usemoblemory-connerage-inderabledsswithSimpleDatateTypes.1)NumpyArsofferVerverVerverVerverVersAtility andPerformanceForlargedForlargedAtatasetSetsAtsAndAtasEndCompleXoper.2)

CTYPES模塊與Python中的數組有何關係?CTYPES模塊與Python中的數組有何關係?Apr 24, 2025 pm 03:45 PM

ctypesallowscreatingingangandmanipulatingc-stylarraysinpython.1)usectypestoInterfacewithClibrariesForperfermance.2)createc-stylec-stylec-stylarraysfornumericalcomputations.3)passarraystocfunctions foreforfunctionsforeffortions.however.however,However,HoweverofiousofmemoryManageManiverage,Pressiveo,Pressivero

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

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

熱工具

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中