小工具 - linux工控机自动上报ip到服务器
前言
自己有一个小工控机,安装了debian系统。工控机使用wifi联网,但是wifi分配的ip总是变,小工控机没有屏幕,无法通过桌面查看ip,这就导致工控机ip变化后无法ssh到工控机上。
思路:
- 工控机添加定时任务,每隔1min扫描制定网卡的ip,并上报给云服务器;
- 云服务器收到ip后,检查ip是否变化,如果变化了就发邮件通知。
(工控机也可以自己检测并发邮件,这里主要是练习目的)
正文
工控机部署:
项目路径:/root/send_ip/
- 检测并发送ip脚本 send_ip.sh
#!/bin/bash
# 网卡名称
# CARD_NAME=wlp2s0
CARD_NAME=wlx6c1ff737422f
# 获取信息
ip=`/usr/sbin/ifconfig ${CARD_NAME}|grep inet|grep -v inet6|awk -F ' ' '{print $2}'`
mac=`/usr/sbin/ifconfig ${CARD_NAME}|grep ether|awk -F ' ' '{print $2}'`
# 发送消息
curl -X POST -H 'Content-Type: application/json' -d "{\"ip\":\"${ip}\",\"mac\":\"${mac}\"}" http://xxx.xxx.xxx.xxx/terminalIp/sendIp
- 添加定时任务
*/1 * * * * cd /root/send_ip/ && ./send_ip.sh
服务器部署
- http server
getIp.py
#-*- coding:utf-8 -*-
from flask import Flask, request,jsonify
import yagmail
import os
import logging
app = Flask(__name__)
last_ip="lastIp.tmp"
# 配置日志
logging.basicConfig(filename='app.log', level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s')
@app.route("/sendIp", methods=['POST'])
def sendIp():
json_data = request.json
app.logger.info(json_data)
ip_new = json_data.get("ip")
global last_ip
if os.path.exists(last_ip):
with open(last_ip,"r") as f:
ip_old=f.read()
if ip_old is not None and ip_old != ip_new:
yag = yagmail.SMTP(user="xxxxxx@qq.com", password="xxxxxx", host="smtp.qq.com")
cc_list=["aaa@qq.com","bbb@qq.com","ccc@qq.com"]
yag.send(to=cc_list, subject="intel ip", contents=ip_new)
with open(last_ip,"w") as f:
f.write(ip_new)
else:
yag = yagmail.SMTP(user="xxxxxx@qq.com", password="xxxxxx", host="smtp.qq.com")
yag.send(to="aaa0@qq.com", subject="intel ip", contents=ip_new)
with open(last_ip,"w") as f:
f.write(ip_new)
return jsonify("ok")
if __name__ == "__main__":
app.run(host="0.0.0.0", port=12121, debug=True)
启动脚本
start.sh
#!/bin/bash
APP_NAME="getIp"
pids=`ps -ef|grep $APP_NAME|grep -v grep|awk -F ' ' '{print $2}'`
if [[ $pids != "" ]];then
echo "start kill $pids"
kill -9 $pids
fi
nohup python3 $APP_NAME.py > $APP_NAME.log 2>&1 &