14 三月, 2025

thumbnail

小白写了一个手机扫码配置网络的脚本

这脚本是我用AI写的哈,本人完全不会写哈,只是分享出来大家一起学习。 [有能力的大佬可以完美的优化下。~~~~

怎么上传不了附件

下面是脚本文,保存*.sh 执行就可以了。

#!/bin/bash
确保以 root 用户运行脚本
if [ "$(id -u)" -ne 0 ]; then
echo "此脚本需要 root 权限,请以 root 用户运行。"
exit 1
fi
更新系统并安装必要的软件包
echo "正在更新系统并安装必要的软件包..."
apt-get update
apt-get install -y hostapd dnsmasq python3 python3-pip qrencode wget kmod
安装 Flask
pip3 install flask
配置无线网卡
echo "正在配置无线网卡..."
cat <<EOF > /etc/network/interfaces.d/wlan0
auto wlan0
iface wlan0 inet static
address 192.168.42.1
netmask 255.255.255.0
gateway 192.168.42.1
dns-nameservers 8.8.8.8
EOF
配置 hostapd
echo "正在配置 hostapd..."
cat <<EOF > /etc/hostapd/hostapd.conf
interface=wlan0
driver=nl80211
ssid=MyLinuxAP
hw_mode=g
channel=6
macaddr_acl=0
auth_algs=1
ignore_broadcast_ssid=0
wpa=2
wpa_passphrase=123456789
wpa_key_mgmt=WPA-PSK
wpa_pairwise=TKIP
rsn_pairwise=CCMP
EOF
配置 dnsmasq
echo "正在配置 dnsmasq..."
cat <<EOF > /etc/dnsmasq.conf
interface=wlan0
dhcp-range=192.168.42.2,192.168.42.20,255.255.255.0,24h
port=53
server=8.8.8.8
EOF
停止并禁用服务
echo "正在停止并禁用服务..."
systemctl stop hostapd
systemctl stop dnsmasq
systemctl disable hostapd
systemctl disable dnsmasq
取消屏蔽服务
echo "正在取消屏蔽服务..."
systemctl unmask hostapd
systemctl unmask dnsmasq
启动服务
echo "正在启动服务..."
systemctl enable hostapd
systemctl enable dnsmasq
systemctl restart hostapd
systemctl restart dnsmasq
创建 Flask 应用
echo "正在创建 Flask 应用..."
cat <<EOF > /usr/local/bin/app.py
from flask import Flask, request, jsonify, render_template_string
import subprocess
app = Flask(name)
@app.route('/')
def index():
return render_template_string('''
<h1>连接到 WiFi</h1>
<div id="wifi-list"></div>
<script>
fetch('/scan')
.then(response => response.json())
.then(data => {
const wifiList = document.getElementById('wifi-list');
data.forEach(wifi => {
const listItem = document.createElement('div');
listItem.textContent = `\${wifi.ssid} (\${wifi.signal} dBm)`;
listItem.onclick = () => {
const password = prompt(`Connecting to \${wifi.ssid}. Enter password:`);
fetch('/connect', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({ssid: wifi.ssid, password: password})
}).then(response => response.json())
.then(data => alert(data.status === 'success' ? 'Connected!' : 'Failed: ' + data.message));
};
wifiList.appendChild(listItem);
});
});
</script>
''')
@app.route('/scan')
def scan_wifi():
result = subprocess.run(["nmcli", "-t", "-f", "IN-USE,SSID,SIGNAL,SECURITY", "dev", "wifi"], capture_output=True, text=True)
networks = result.stdout.strip().split('\n')
wifi_list = []
for network in networks:
if network.strip():
parts = network.split(':')
wifi_list.append({
'ssid': parts[1].strip(),
'signal': parts[2].strip(),
'security': parts[3].strip()
})
return jsonify(wifi_list)
@app.route('/connect', methods=['POST'])
def connect_wifi():
data = request.json
ssid = data.get('ssid')
password = data.get('password')
if ssid and password:
result = subprocess.run(
["nmcli", "dev", "wifi", "connect", ssid, "password", password],
capture_output=True, text=True
)
if result.returncode == 0:
return jsonify({"status": "success"})
else:
return jsonify({"status": "error", "message": result.stderr})
return jsonify({"status": "error", "message": "Invalid input"})
if name == 'main':
app.run(host='0.0.0.0', port=5001)
EOF
开放相关端口
echo "正在开放相关端口..."
ufw allow 53
ufw allow 5001
ufw allow 80
ufw allow 443
启动 Flask 应用
echo "正在启动 Flask 应用..."
python3 /usr/local/bin/app.py &
生成二维码
echo "正在生成二维码..."
qrencode -o /usr/local/bin/qr.png "http://192.168.42.1:5001"
echo "部署完成!"
echo "请扫描 /usr/local/bin/qr.png 中的二维码以配置 WiFi。"





欢迎投稿(技术分享、原创教程)至本站机器人: blog#mige.eu.org
 
thumbnail

SSH登录发送告警信息到邮箱

前言

自从开放端口到公网后,每次查看SSH日志,总有一堆国外肉鸡在疯狂访问,于是想搞个远程登录报警(可能也什么卵用,但至少被爆破后能知道,可以及时修改密码)。

原理

将自动发送邮件的脚本放到.bashrc中,一旦通过SSH登录,就会自动运行,并获取登录信息发送到对应邮箱上。

方法

步骤一:获取邮箱的应用密码(此处以QQ邮箱为例)

参考链接:https://laowangblog.com/qq-mail-smtp-service.html

步骤二:编写邮件发送脚本,保存为send_email.py

#!/usr/bin/python  # -*- coding: UTF-8 -*-  import smtplib  from email import encoders  from email.header import Header  from email.mime.text import MIMEText  from email.utils import parseaddr, formataddr  import sys    def send_mail(dtime,duser,dip,dhostname):      #基础信息      # from_addr = input("From:")      from_addr = "[email protected]" # 发送邮件地址      password = "xxxxx"  # 邮箱应用密码,步骤一获取      #to_addr = from_addr      to_addr = ["[email protected]"] # 接收邮件地址      # password = raw_input("Password:")      # to_addr = input("To:")      smtp_server = "smtp.qq.com"      mimetex = '[server0x]您的机器:',dhostname,',于:',dtime,',被IP: ',dip,' 以账号:',duser,' 进行登录,请确认是否是本人。'      #构造邮件      msg = MIMEText(''.join(mimetex), 'plain', 'utf-8')      msg['From'] = "{}".format(from_addr)      msg['To']   = ",".join(to_addr)      msg['Subject'] = Header("来自Server Monitor", 'utf-8').encode()      #发送邮件      server = smtplib.SMTP_SSL(smtp_server, 465)      #server.set_debuglevel(1)      server.login(from_addr, password)      server.sendmail(from_addr, to_addr, msg.as_string())      server.quit()    if __name__ == "__main__":      send_mail(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4])

步骤三:获取登录信息,并调用邮件脚本,保存为sshrc.sh

#!/bin/sh    #获取登录者的用户名  user=$USER  #获取登录者的IP地址  ip=${SSH_CLIENT%% *}  #获取登录的时间  time=$(date +%F%t%k:%M)  #服务器的IP地址  hostname=$(hostname)  echo "content=$time,$user,$ip,$hostname" > /dev/null 2>&1  /usr/bin/python3 /opt/send_email.py  "$time" "$user" "$ip" "$hostname" > /dev/null 2>&1

步骤四:将sshrc.sh脚本放到.bashrc中,添加前建议先在终端测试一下

运行 vi ~/.bashrc 即可打开,然后在文件末尾处添加 /opt/sshrc.sh > /dev/null
到此全部添加完成,可以关闭终端,然后连接SSH试一下。。。






欢迎投稿(技术分享、原创教程)至本站机器人: blog#mige.eu.org
 

About

搜索此博客