Python之自動獲取公網(wǎng)IP的實(shí)例講解
0.預(yù)備知識
0.1 SQL基礎(chǔ)
ubuntu、Debian系列安裝:
root@raspberrypi:~/python-script# apt-get install mysql-server
Redhat、Centos 系列安裝:
[root@localhost ~]# yum install mysql-server
登錄數(shù)據(jù)庫
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是主機(jī)
創(chuàng)建數(shù)據(jù)庫、創(chuàng)建數(shù)據(jù)表
創(chuàng)建數(shù)據(jù)庫語法如下
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)]>
創(chuàng)建數(shù)據(jù)表語法如下
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
創(chuàng)建數(shù)據(jù)庫ServiceLogs
MariaDB [(none)]> CREATE DATABASE `ServiceLogs`
創(chuàng)建數(shù)據(jù)表
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
表內(nèi)容的查詢
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 進(jìn)入解壓后目錄 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("主機(jī)","用戶名","密碼","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#
執(zhí)行完成后可以mysql客戶端SELECT語句查看結(jié)果
1.需求
1.1 需求
由于寬帶每次重啟都會重新獲得一個(gè)新的IP,那么在這種狀態(tài)下,在進(jìn)行ssh連接的時(shí)候會出現(xiàn)諸多的不便,好在之前還有花生殼軟件,它能夠通過域名來找到你的IP地址,進(jìn)行訪問,這樣是最好的,不過最近花生殼也要進(jìn)行實(shí)名認(rèn)證才能夠使用,于是乎,這就催發(fā)了我寫一個(gè)python腳本來獲取公網(wǎng)IP的沖動。
實(shí)現(xiàn)效果:當(dāng)IP變更時(shí),能夠通過郵件進(jìn)行通知,且在數(shù)據(jù)庫中寫入數(shù)據(jù)
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("主機(jī)","用戶名","密碼","庫名")
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>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.效果
收到的郵件如下:

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

把腳本放入crontab中,讓它執(zhí)行定時(shí)任務(wù)即可
以上這篇Python之自動獲取公網(wǎng)IP的實(shí)例講解就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python文件操作及內(nèi)置函數(shù)flush原理解析
這篇文章主要介紹了Python文件操作及內(nèi)置函數(shù)flush原理解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-10-10
python單向循環(huán)鏈表原理與實(shí)現(xiàn)方法示例
這篇文章主要介紹了python單向循環(huán)鏈表原理與實(shí)現(xiàn)方法,結(jié)合實(shí)例形式詳細(xì)分析了Python單向循環(huán)鏈表概念、原理、定義及使用方法,需要的朋友可以參考下2019-12-12
python3格式化字符串 f-string的高級用法(推薦)
從Python 3.6開始,f-string是格式化字符串的一種很好的新方法。與其他格式化方式相比,它們不僅更易讀,更簡潔,不易出錯(cuò),而且速度更快!本文重點(diǎn)給大家介紹python3格式化字符串 f-string的高級用法,一起看看吧2020-03-03

