前言
当我们需要远程连接自己的Linux计算机时,可以使用ssh命令,但是需要我们获取目标计算机的公网ip。以下是使用Python实现的开机自动获取本地并发送至指定邮箱的小脚本。
?
实现步骤
1.引入库
需要获取公网地址,我这里选择的是通过requests库,发送邮箱需要使用smtplip库。
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import requests
2.地址获取
代码如下:
def getUrl(url):
try:
r = requests.get(url)
r.raise_for_status() # 抛出异常
r.encoding = r.apparent_encoding
return r.text
except:
return "请求发生错误错误"
获取IP地址的路径为: http://ip.42.pl/raw
3.邮件发送
代码如下:
# 发送邮件
def send_msg(urlText):
fromaddr = '*********@qq.com' # 发送邮件的邮箱
password = 'aaaaaaaaaaaaaaaa' # 邮箱的授权码,注意不是密码
toaddrs = ['#########@qq.com'] #目标邮箱
m = MIMEMultipart()
content = urlText # 邮件正文内容
textApart = MIMEText(content)
m.attach(textApart)
m['Subject'] = 'Linux IP' # 邮件标题
try:
server = smtplib.SMTP('smtp.qq.com')
server.login(fromaddr, password)
server.sendmail(fromaddr, toaddrs, m.as_string())
server.quit()
print('success!')
except smtplib.SMTPException as e:
print('error:', e) # 打印错误
4.Linux开机自启脚本
1.修改/etc/rc.d/rc.local为
#!/bin/bash # THIS FILE IS ADDED FOR COMPATIBILITY PURPOSES # # It is highly advisable to create own systemd services or udev rules # to run scripts during boot instead of using this file. # # In contrast to previous versions due to parallel execution during boot # this script will NOT be run after all other services. # # Please note that you must run 'chmod +x /etc/rc.d/rc.local' to ensure # that this script will be executed during boot. ? touch /var/lock/subsys/local source /xxx/Desktop/main.sh
2.修改文件权限
chmod 777 rc.local
5.完整代码实现
#!/usr/bin/python
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import requests
def getUrl(url):
try:
r = requests.get(url)
r.raise_for_status() # 抛出异常
r.encoding = r.apparent_encoding
return r.text
except:
return "请求发生错误错误"
# 发送邮件
def send_msg(urlText):
fromaddr = ''
password = ''
toaddrs = ['']
m = MIMEMultipart()
content = urlText
textApart = MIMEText(content)
m.attach(textApart)
m['Subject'] = 'Linux IP'
try:
server = smtplib.SMTP('smtp.qq.com')
server.login(fromaddr, password)
server.sendmail(fromaddr, toaddrs, m.as_string())
server.quit()
print('success!')
except smtplib.SMTPException as e:
print('error:', e) # 打印错误
if __name__ == '__main__':
url = 'http://ip.42.pl/raw'
print(getUrl(url))
send_msg(getUrl(url))
|