아래 편집기는 Python에서 공용 IP를 자동으로 얻는 방법에 대한 예를 제공합니다. 편집자님이 꽤 좋다고 생각하셔서 지금 공유하고 모두에게 참고용으로 드리고자 합니다. 에디터와 함께 구경해보세요
0. 예비 지식
0.1 SQL 기초
ubuntu, 데비안 시리즈 설치:
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
Querying table content
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 $?
Connect 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이 성공적으로 출력되면 연결이 정상임을 의미합니다.
Python MySQL 삽입 문
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 주소를 알아낼 수 있는 Peanut Shell 소프트웨어가 있었는데, 최근에는 Peanut Shell에서도 사전에 실명 인증을 요구하고 있습니다. 사용할 수 있으므로 공용 IP를 얻기 위해 Python 스크립트를 작성하라는 메시지가 표시되었습니다.
성취 효과: IP가 변경되면 이메일로 알림을 받을 수 있으며 데이터베이스에 데이터를 쓸 수 있습니다.
다른 코드는 그릴게 없습니다
2.
2.1.1
파이썬 코드 작성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['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.Effect
받은 이메일은 다음과 같습니다.
SELECT를 사용하여 테이블을 보면 효과는 다음과 같습니다.
스크립트를 crontab에 넣고 예약된 작업을 실행하게 하세요
위 내용은 Python에서 자동으로 공용 IP를 얻는 방법에 대한 설명 예의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

Arraysinpython, 특히 비밀 복구를위한 ArecrucialInscientificcomputing.1) theaRearedFornumericalOperations, DataAnalysis 및 MachinELearning.2) Numpy'SimplementationIncensuressuressurations thanpythonlists.3) arraysenablequick

Pyenv, Venv 및 Anaconda를 사용하여 다양한 Python 버전을 관리 할 수 있습니다. 1) PYENV를 사용하여 여러 Python 버전을 관리합니다. Pyenv를 설치하고 글로벌 및 로컬 버전을 설정하십시오. 2) VENV를 사용하여 프로젝트 종속성을 분리하기 위해 가상 환경을 만듭니다. 3) Anaconda를 사용하여 데이터 과학 프로젝트에서 Python 버전을 관리하십시오. 4) 시스템 수준의 작업을 위해 시스템 파이썬을 유지하십시오. 이러한 도구와 전략을 통해 다양한 버전의 Python을 효과적으로 관리하여 프로젝트의 원활한 실행을 보장 할 수 있습니다.

Numpyarrayshaveseveraladvantagesstandardpythonarrays : 1) thearemuchfasterduetoc 기반 간증, 2) thearemorememory-refficient, 특히 withlargedatasets 및 3) wepferoptizedformationsformationstaticaloperations, 만들기, 만들기

어레이의 균질성이 성능에 미치는 영향은 이중입니다. 1) 균질성은 컴파일러가 메모리 액세스를 최적화하고 성능을 향상시킬 수 있습니다. 2) 그러나 유형 다양성을 제한하여 비 효율성으로 이어질 수 있습니다. 요컨대, 올바른 데이터 구조를 선택하는 것이 중요합니다.

tocraftexecutablepythonscripts, 다음과 같은 비스트 프랙티스를 따르십시오 : 1) 1) addashebangline (#!/usr/bin/envpython3) tomakethescriptexecutable.2) setpermissionswithchmod xyour_script.py.3) organtionewithlarstringanduseifname == "__"

numpyarraysarebetterfornumericaloperations 및 multi-dimensionaldata, mumemer-efficientArrays

numpyarraysarebetterforheavynumericalcomputing, whilearraymoduleisiMoresuily-sportainedprojectswithsimpledatatypes.1) numpyarraysofferversatively 및 formanceforgedatasets 및 complexoperations.2) Thearraymoduleisweighit 및 ep

ctypesallowscreatingandmanipulatingC-stylearraysinPython.1)UsectypestointerfacewithClibrariesforperformance.2)CreateC-stylearraysfornumericalcomputations.3)PassarraystoCfunctionsforefficientoperations.However,becautiousofmemorymanagement,performanceo


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

WebStorm Mac 버전
유용한 JavaScript 개발 도구

DVWA
DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는

SublimeText3 영어 버전
권장 사항: Win 버전, 코드 프롬프트 지원!

에디트플러스 중국어 크랙 버전
작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기
