cpolar:通过脚本自动更新主机名称和端口号进行内网穿透【免费版】

cpolar 的免费版经常会重新分配 HostName 和 Port,总是手动修改太过麻烦,分享一下自动更新配置文件并进行内网穿透的方法。


假设你已经配置好了服务器端的 cpolar。

配置 ssh config

该部分原文:SSH 远程登录服务器跑实验(含内网穿透)

现在配置一下主机的 ssh 文件。

vim ~/.ssh/config

config 参数:

  • Host: 别名,可以直接用于 ssh 登录
  • Hostname: IP 地址
  • Port: SSH 端口号(如果做了内网穿透,则需要填写对应的端口号)
    • 比如:下图对应的是 10387
      image
  • User: 登录的用户名
  • PreferredAuthentications: 指定客户端的认证方法为公钥
  • IdentityFile: 当前指的是私钥路径

P.S: 具体的参数信息可以通过 man ssh_config 查看

下面是配置文件样例(以 Ubuntu 为例):

Host Ubuntu-Nat-DDNS					# 你可以改成你想要的名字
	HostName 3.tcp.vip.cpolar.cn		# 填写公网ip
	Port 10387							# 公网 ip 对应的 端口号
	User xx								# 远程主机的登录名
	PreferredAuthentications publickey
    IdentityFile ~/.ssh/id_rsa_ubuntu	# 改成对应的私钥路径或者将其重命名

现在可以通过 ssh Ubuntu-Nat-DDNS 直接登陆。

但 cpolar 的免费版经常会重新分配 HostName 和 Port,所以需要配置一个自动更新的脚本。

编写脚本

vim ~/scripts/update_ssh_cfg.sh

以下是 Python 脚本代码:

#!/usr/bin/env python

import requests
from bs4 import BeautifulSoup
import re

# 登录函数
def login(login_url, username, password, csrf_token):
    session = requests.Session()
    payload = {
        'login': username,
        'password': password,
        'csrf_token': csrf_token
    }
    response = session.post(login_url, data=payload)
    if response.status_code == 200:
        return session
    else:
        raise Exception('登录失败')

# 获取目标字符串函数
def get_target_string(session, url):
    response = session.get(url)
    soup = BeautifulSoup(response.text, 'html.parser')
    target_element = soup.find('a', href="#ZgotmplZ")
    if target_element:
        return target_element.text
    else:
        raise Exception('隧道可能未激活')

# 提取 HostName 和 Port 函数
def extract_hostname_and_port(target_string):
    pattern = r'tcp://(.*?):(\d+)'
    matches = re.match(pattern, target_string)
    if matches:
        hostname = matches.group(1)
        port = matches.group(2)
        return hostname, port
    else:
        raise Exception('未找到匹配的字符串')

# 更新配置文件函数
def update_config_file(filename, hostname, port):
    with open(filename, "r") as file:
        content = file.readlines()

    is_modified = False
    for i, line in enumerate(content):
        if line.strip() == "Host Ubuntu-NAT-DDNS": # 如果使用的是其他别名,在这里修改
            hostname_line = content[i + 1].strip()
            if hostname_line.startswith("HostName") and hostname_line.split(" ")[-1] != hostname:
                content[i + 1] = f"    HostName {hostname}\n"
                is_modified = True
            port_line = content[i + 2].strip()
            if port_line.startswith("Port") and port_line.split(" ")[-1] != port:
                content[i + 2] = f"    Port {port}\n"
                is_modified = True

    if not is_modified:
        print("HostName 和 Port 未发生变化,无需更新。")
    else:
        with open(filename, "w") as file:
            file.writelines(content)
        print("已更新配置。")

# 主程序
def main():
    # 配置项
    username = ''
    password = ''
    csrf_token = ''
    login_url = 'https://dashboard.cpolar.com/login'
    content_url = 'https://dashboard.cpolar.com/status'
    config_filename = "/Users/home/.ssh/config"

    try:
        # 登录
        session = login(login_url, username, password, csrf_token)

        # 获取目标字符串
        target_string = get_target_string(session, content_url)
        print(target_string)

        # 提取 HostName 和 Port
        hostname, port = extract_hostname_and_port(target_string)
        print("HostName:", hostname)
        print("Port:", port)

        # 更新配置文件
        update_config_file(config_filename, hostname, port)

    except Exception as e:
        print("发生错误:", str(e))

# 运行主程序
if __name__ == "__main__":
    main()

为脚本添加执行权限:

chmod +x ~/scripts/update_ssh_cfg.sh

如果你不是使用 Ubuntu-NAT-DDNS 作为别名,则修改下方标注出的代码:

修改别名

另外,你需要填充上面的 usernamepasswordcsrf_token,其中 csrf_token 可以通过下面的方式获取。

获取 csrf_token

打开登陆界面

访问 https://dashboard.cpolar.com/login

login

Safari

点击开发->显示网页检查器 或者使用 option + command + L 打开网页检查器

网页检查器

输入账号密码进行登录,点击get-started -> 标头 -> 请求数据

请求数据

然后你就可以看到三个我们所需要的字段,将其填充回代码部分。
获取字段

Chrome

使用 F12 打开开发者工具,进入 Network,点击 login -> Payload 查看字段。
Chrome

通过以上步骤获取 usernamepasswordcsrf_token 后,填入代码并使用esc + :wq保存脚本。

设置别名

现在,我们可以使用 update_ssh_cfg && ssh Ubuntu-NAT-DDNS 自动完成内网穿透。

为了方便,我们可以为这段代码设置别名。首先,打开 .bashrc 或 .zshrc 文件(取决于你使用的 shell):

vim ~/.bashrc  # 或者 vim ~/.zshrc

在文件末尾添加以下别名配置:

alias update_ssh_cfg='~/scripts/update_ssh_cfg.sh'
alias SSH_UBUNTU='update_ssh_cfg && ssh Ubuntu-NAT-DDNS'

保存并关闭文件后,运行以下命令使修改生效:

source ~/.bashrc  # 或者 source ~/.zshrc

现在,可以使用 SSH_UBUNTU 自动更新 HostName 和 Port,并完成内网穿透。

  • 17
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Hoper.J

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值