The following small series for everyone to bring a Python automatic access to public IP examples of interpretation. Small series feel very good, now share to everyone, also for everyone to make a reference. Let's take a look at it with a little knitting.
0. Pre-knowledge
0.1 SQL Basics
Ubuntu, Debian Series installation:
root@raspberrypi:~/python-script# Apt-get Install Mysql-server
Redhat, Centos Series installation:
[Root@localhost ~]# Yum Install Mysql-server
Log in to Database
pi@raspberrypi:~ $ mysql-uroot-p-hlocalhostenter password:welcome to the MariaDB Monitor. Commands End With; or \g.your MariaDB connection ID is 36Server version:10.0.30-mariadb-0+deb8u2 (Raspbian) Copyright (c), Oracle, MariaDB Corporation Ab and others. Type ' help ', ' or ' \h ' for help. Type ' \c ' to clear the current input statement. MariaDB [(None)]>
Where MySQL is the client command-U is the specified user-P is the password-H is the host
Create a database, create a data table
Create DATABASE syntax as follows
MariaDB [(None)]> help create DatabaseName: ' Create database ' Description:Syntax:CREATE {database | SCHEMA} [IF not EXISTS] db_name [create_specification] ... create_specification: [DEFAULT] CHARACTER SET [=] charset_name | [DEFAULT] COLLATE [=] collation_namecreate database creates a database with the given name. To use thisstatement, you need the CREATE privilege for the database. Createschema is a synonym for CREATE DATABASE. URL:HTTPS://MARIADB.COM/KB/EN/CREATE-DATABASE/MARIADB [(None)]>
Create data table syntax as follows
MariaDB [(None)]> help create TableName: ' 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
Create a database Servicelogs
MariaDB [(None)]> CREATE DATABASE ' servicelogs '
Create a data table
MariaDB [(None)]> CREATE TABLE ' python_ip_logs ' (' Serial_number ' bigint () not NULL auto_increment, ' Time ' datetime D Efault null, ' old_data ' varchar () default NULL, ' new_data ' varchar (default NULL, PRIMARY KEY (' Serial_number ')) ENGI Ne=innodb auto_increment=3 DEFAULT charset=latin1
Query for table content
MariaDB [servicelogs]> SELECT * from Python_ip_logs; Empty Set (0.00 sec)
0.2 python connection operation MySQL
Module Download Installation
Download path: Https://pypi.python.org/pypi/MySQL-python
Installation:
Install: Unzip unzip mysql-python-1.2.5.zip into the unpacked directory CD mysql-python-1.2.5/install dependent apt-get Install Libmysqlclient-dev mount Python setup.py Install Okecho $ if it is 0?
Connect to MySQL
root@raspberrypi:~/python-script# cat p_mysql_3.py #!/usr/bin/env pythonimport mysqldbtry: conn = MySQLdb.connect ("Host", "username", "password", "Servicelogs") Print ("Connect MySQL successful") except: print ("Connect MySQL Fail") root@raspberrypi:~/python-script#
If the output connect Mysql successful the connection OK
Python MySQL INSERT statement
root@raspberrypi:~/python-script# cat p_mysql1.py #!/usr/bin/env pythonimport mysqldbdb = 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#
The MySQL client SELECT statement can view the results after execution is complete
1. Requirements
1.1 Requirements
Because the broadband each reboot will regain a new IP, then in this state, in the SSH connection when there will be a lot of inconvenience, fortunately, before the peanut shell software, it can find your IP address through the domain name, access, so that is the best, But recently the peanut shell also must carry on the real-name authentication to be able to use, thus, this presses me to write a Python script to obtain the public network IP impulse.
Implementation: When IP changes, can be notified by mail, and write data in the database
1.2 General ideas
1.3 Flowchart
There's nothing in the other code that's good to draw.
2. Code Writing
2.1.1 Writing Python code
getnetworkip.py
root@raspberrypi:~/python-script# cat getnetworkip.py #!/usr/bin/env python# coding:utf-8import requestsimport send_ Mailimport savedbdef 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 falseif __name__== "__main__": Main () root@raspberrypi:~/ python-script#
savedb.py
root@raspberrypi:~/python-script# cat savedb.py#!/usr/bin/env pythonimport mysqldbimport osimport timedirname = "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 R Ead_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) GE Neral_files (NEW_IP) write_db (NOWTIME,OLD_IP,NEW_IP) return True else:return falsedef write_db (nowtime,old_ip,ne W_IP): db = MySQLdb.connect ("host", "username", "password", "library name") cursor = db.cursor () sql = "" "INSERT into Python_ip_logs VAL UES (DEFAULT, "%s", "%s", "%s") "" "% (NOWTIME,OLD_IP,NEW_IP) try:cursor.execute (SQL) Db.commit () EXCEPT:DB.R Ollback () db.close () Root@raspberrypi:~/python-script#
send_mail.py
root@raspberrypi:~/python-script# cat send_mail.py#!/usr/bin/env Pythonimport smtplibimport email.mime.textdef Sammail (htmlstring): HOST = "smtp.163.com" SUBJECT = "subject" to = "The other's email address" from = "where is it" remask = "The IP address has been Changed "MSG = Email.mime.text.MIMEText (" "" 3. Effects
The message received is as follows:
Using Select to view the table, the effect is as follows:
Put the script in the crontab and let it perform the scheduled task