Python: Automatically Obtaining public IP addresses; python: obtaining ip addresses
Automatic Acquisition of Public IP addresses in Python
September 30, 2017
0.
Prerequisites
0.1 SQL Basics
Ubuntu and Debian series installation:
1 root@raspberrypi:~/python-script# apt-get install mysql-server
Redhat and Centos series installation:
1 [root@localhost ~]# yum install mysql-server
Log on to the database
1 pi@raspberrypi:~ $ 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)]>
Here, mysql is the Client Command-u is the specified user-p is the password-h is the host
Create databases and data tables
The database creation syntax is as follows:
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_name10 | [DEFAULT] COLLATE [=] collation_name11 12 CREATE DATABASE creates a database with the given name. To use this13 statement, you need the CREATE privilege for the database. CREATE14 SCHEMA is a synonym for CREATE DATABASE.15 16 URL: https://mariadb.com/kb/en/create-database/17 18 19 MariaDB [(none)]>
The table creation syntax is as follows:
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_name13 [(create_definition,...)]14 [table_options]15 [partition_options]16 select_statement
Create Database ServiceLogs
1 MariaDB [(none)]> CREATE DATABASE `ServiceLogs`
Create a data table
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
Table Content Query
1 MariaDB [ServiceLogs]> select * from python_ip_logs;2 Empty set (0.00 sec)
0.2 connect to MySQL using python
Download and install modules
Https://pypi.python.org/pypi/MySQL-python download path
Installation:
1 install: 2 unzip 3 unzip MySQL-python-1.2.5.zip 4 enter the unzip directory 5 cd MySQL-python-1.2.5/6 install dependency 7 apt-get install libmysqlclient-dev 8 install 9 python setup. py install10 if it is 0, install OK11 echo $?
Connect to Mysql
1 root @ raspberrypi :~ /Python-script # cat p_mysql_3.py 2 #! /Usr/bin/env python 3 4 import MySQLdb 5 6 try: 7 conn = MySQLdb. connect ("host", "User Name", "password", "ServiceLogs") 8 print ("Connect Mysql successful") 9 fingerprint T: 10 print ("Connect MySQL Fail ") 11 root @ raspberrypi :~ /Python-script #
If Connect Mysql successful is output, the connection is OK.
Python MySQL insert statement
1 root@raspberrypi:~/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 root@raspberrypi:~/python-script#
After execution, you can view the results using the mysql client SELECT statement.
1.
Requirement
1.1 requirements
Because every time the bandwidth is restarted, it will get a new IP address, so in this status, there will be a lot of inconvenience during the ssh connection, fortunately there is a peanut shell software before, it is the best way to find your IP address and access it through the domain name. However, you have to perform real-name authentication before using it, this reminds me of the impulse to write a python script to get a public IP address.
Effect: When the IP address is changed, you can send an email notification and write data to the database.
1.2 General ideas
1.3 Flowchart
No other code is easy to draw.
2.
Code Writing
2.1.1 compile python code
Getnetworkip. py
1 root@raspberrypi:~/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.text13 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 False28 29 if __name__=="__main__" :30 main()31 root@raspberrypi:~/python-script#
Savedb. py
1 root @ raspberrypi :~ /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_String14 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 True36 else: 37 return False38 39 40 def write_db (NowTime, Old_ip, New_ip ): 41 db = MySQLdb. connect ("host", "User Name", "password", "Database Name") 42 43 cursor = db. Cursor () 44 45 SQL = "46 INSERT INTO python_ip_logs 47 VALUES48 (DEFAULT," % s ") 49 "% (NowTime, Old_ip, New_ip) 50 51 try: 52 cursor.exe cute (SQL) 53 db. commit () 54 TB: 55 db. rollback () 56 57 db. close () 58 root @ raspberrypi :~ /Python-script #
Send_mail.py
1 root @ raspberrypi :~ /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 = "topic" 10 TO = "recipient's email address" 11 FROM = "FROM where" 12 Remask = "The IP address has been changed" 13 14 msg = email. mime. text. MIMEText ("15
3. Results
The received email is as follows:
Use SELECT to view the table. The result is as follows:
Put the script in crontab and let it execute the scheduled task.