Heim  >  Artikel  >  Backend-Entwicklung  >  Beispielerklärung zum automatischen Erhalten einer öffentlichen IP in Python

Beispielerklärung zum automatischen Erhalten einer öffentlichen IP in Python

黄舟
黄舟Original
2017-10-09 10:40:141559Durchsuche

Der folgende Editor zeigt Ihnen ein Beispiel dafür, wie Sie in Python automatisch eine öffentliche IP erhalten. Der Herausgeber findet es ziemlich gut, deshalb werde ich es jetzt mit Ihnen teilen und es allen als Referenz geben. Schauen Sie doch einmal mit dem Editor vorbei

0.1 SQL Grundlegende Installation von

Ubuntu, Debian-Serie:

Redhat, Centos-Serie Installation:


root@raspberrypi:~/python-script# apt-get install mysql-server

Melden Sie sich bei der Datenbank an


 [root@localhost ~]# yum install mysql-server
wo sich MySQL befindet der Client-Befehl -u ist der angegebene Benutzer -p ist das Passwort -h ist der Host

Erstellen Sie eine Datenbank und erstellen Sie eine Datentabelle


Die Syntax zum Erstellen einer Datenbank lautet wie folgt

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)]>

Die Syntax zum Erstellen einer Datentabelle lautet wie folgt


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)]>
Datenbank-ServiceLogs erstellen


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
Datentabelle erstellen


MariaDB [(none)]> CREATE DATABASE `ServiceLogs`
Abfrage von Tabelleninhalten


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

0.2 Python-Verbindungsbetrieb MySQL


 MariaDB [ServiceLogs]> select * from python_ip_logs;
 Empty set (0.00 sec)
Modul-Download und Installation

Download-Pfad: https://pypi. python.org/pypi/MySQL-pythonInstallation:

Mysql verbinden


安装:
解压
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 $?
Wenn „Connect Mysql erfolgreich“ ausgegeben wird, ist die Verbindung in Ordnung

Python MySQL-Einfügeanweisung


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#

Nachdem die Ausführung abgeschlossen ist, Sie können die Ergebnisse mit der SELECT-Anweisung des MySQL-Clients anzeigen


1. Anforderungen

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#

1.1 Anforderungen

Da das Breitband bei jedem Neustart eine neue IP erhält, gibt es in diesem Zustand viele Unannehmlichkeiten beim Herstellen einer SSH-Verbindung. Glücklicherweise gab es zuvor Peanut Shell-Software Sie können Ihre IP-Adresse über den Domänennamen finden und darauf zugreifen, aber seit kurzem erfordert Peanut Shell auch echte Namen. Sie kann nur nach Authentifizierung verwendet werden, daher habe ich ein Python-Skript geschrieben, um die öffentliche IP zu erhalten.

Erfolgseffekt: Wenn sich die IP ändert, kann eine Benachrichtigung per E-Mail gesendet und Daten in die Datenbank geschrieben werden

1.2

Allgemeine Idee

1.3

Flussdiagramm

Andere Codes sind nichts zu zeichnen

2.

Code schreiben

2.1.1 Python-Code schreiben

getnetworkip.py

savedb .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#
send_mail.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#

3 .The Wirkung


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[&#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;)
Die erhaltene E-Mail lautet wie folgt:

Verwenden Sie SELECT, um die Tabelle anzuzeigen. Die Wirkung ist wie folgt:

Fügen Sie das Skript in crontab ein und lassen Sie es geplante Aufgaben ausführen

Das obige ist der detaillierte Inhalt vonBeispielerklärung zum automatischen Erhalten einer öffentlichen IP in Python. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn