news 2026/6/24 3:03:36

linux宝塔面板使用API自动部署更新文件

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
linux宝塔面板使用API自动部署更新文件

次两次更新还好,多网站,多频次更新,还是需要一个简单脚本实现自动化更新部署.

2. 开启API访问

登录宝塔面板,找到设置/面板设置>API接口,点击API接口配置获取接口密钥,以及配置IP白名单.配置图如下

3. 访问签名处理

访问接口时,需要添加签名参数,签名参数生成规是token: md5(str(时间戳) + 密钥MD5),Python实现代码如下

# self.api_key 是在接口配置获取的接口密钥 # 公众号: 小满小慢 def _generate_sign(self) -> dict: now_time = int(time.time()) api_key_md5 = hashlib.md5(self.api_key.encode()).hexdigest() token_str = str(now_time) + api_key_md5 token = hashlib.md5(token_str.encode()).hexdigest() return { 'request_token': token, 'request_time': now_time }

4. 通用请求处理

API所有的请求都需要带上签名信息,我们这里对访问的接口做一个统一的封装,使调用接口只关心业务参数,对一封装代码如下

# self.panel_url 配置的宝塔面板地址 # 公众号: 小满小慢 def _post(self, endpoint: str, data: dict = None) -> dict: if data is None: data = {} sign_params = self._generate_sign() all_data = {**data, **sign_params} url = urljoin(self.panel_url, endpoint) try: response = requests.post( url, data=all_data, timeout=self.request_timeout, verify=False ) response.raise_for_status() result = response.json() if result.get('status') == False: raise Exception(f"地心侠士: API 错误: {result.get('msg', '未知错误')}") return result except requests.exceptions.RequestException as e: raise Exception(f"地心侠士: 请求失败: {e}")

5. 文件上传

文件上传比较特殊,这里需读取本地文件,并上传到服务器指定目录,这里单独封成一个方法.

# 公众号: 小满小慢 # 小游戏: 地心侠士 def upload_file(self, local_path: str, remote_path: str) -> bool: try: file_name = os.path.basename(local_path) file_size = os.path.getsize(local_path) remote_dir = os.path.dirname(remote_path) print(f" 地心侠士 准备上传: {file_name} ({file_size} bytes) -> {remote_path}") sign_data = self._generate_sign() data = { 'f_path': remote_dir, 'f_name': remote_path, 'f_size': file_size, 'f_start': 0, 'request_token': sign_data['request_token'], 'request_time': sign_data['request_time'] } files = { 'blob': (file_name, open(local_path, 'rb'), 'application/octet-stream') } endpoint = '/files?action=upload' url = urljoin(self.panel_url, endpoint) headers = { 'Accept': '*/*', 'Accept-Encoding': 'zh-CN,zh;q=0.9', 'Connection': 'keep-alive' } response = requests.post( url, headers=headers, data=data, files=files, timeout=self.request_timeout, verify=False ) files['blob'][1].close() response.raise_for_status() result = response.json() if result.get('status') == False: raise Exception(f"地心侠士 API 错误: {result.get('msg', '未知错误')}") print(f" 地心侠士 [成功] 文件上传完成: {file_name}") return True except Exception as e: print(f" 地心侠士 [错误] 文件上传失败: {e}") return False

6. 文件解压

文件解压接口,根据文件上传的路径,调用文件解压接口,实现文件解压功能,以及删除解压完成的zip文件,核心代码如下

# remote_zip 是服务上传的zip文件路径 # web_site_path 是网站解压路径 # 公众号: 小满小慢 try: unzip_result = api._post('/files?action=UnZip', { 'sfile': remote_zip, 'dfile': web_site_path, 'encoding': 'utf-8' }) if unzip_result.get('status'): print(f" 地心侠士 [成功] ZIP文件已解压到: {web_site_path}") try: api._post('/files?action=DeleteFile', { 'path': remote_zip }) print(f" 地心侠士 [成功] 已清理临时ZIP文件") except: pass else: print(f" 地心侠士 [警告] 解压可能有问题: {unzip_result.get('msg', '未知错误')}") print(f" 地心侠士 请手动解压: {remote_zip} -> {web_site_path}")

7. 停用启用网站

文件部署完成后,针对后端的任务,如果没有开启热启动,这里我们需要先获取站点信息,然后停用网站,再启动网站

  • 获取网站信息

    # 公众号: 小满小慢 # 返回信息说明: name 网站名称 path 网站路径 site_id 网站ID sites_result = api._post('/data?action=getData', { 'table': 'sites', 'limit': 1000 })
  • 停用网站

    stop_result = api._post('/site?action=SiteStop', { 'id': site_id, 'name': site_name })
  • 启动网站

    start_result = api._post('/site?action=SiteStart', { 'id': site_id, 'name': site_name })

8. 总结

使用脚本自动化部署,最重要的好处就是在脚本编写完成后,完全解放双手,并且不易出错,当然也得做好备份.目前宝塔的API信息不多,当前部署需要的api信息汇总如下

功能接口地址方法
测试连接/system?action=GetNetWorkPOST
文件上传/files?action=uploadPOST
文件解压/files?action=UnZipPOST
删除文件/files?action=DeleteFilePOST
获取网站列表/data?action=getDataPOST
停用网站/site?action=SiteStopPOST
启用网站/site?action=SiteStartPOST
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/6/24 3:01:40

李跳跳自定义规则:彻底告别Android应用弹窗干扰的终极方案

李跳跳自定义规则:彻底告别Android应用弹窗干扰的终极方案 【免费下载链接】LiTiaoTiao_Custom_Rules 李跳跳自定义规则 项目地址: https://gitcode.com/gh_mirrors/li/LiTiaoTiao_Custom_Rules 你是否厌倦了在Android手机上频繁点击"跳过"、"…

作者头像 李华
网站建设 2026/6/24 3:01:00

GitHub Desktop中文汉化终极指南:3分钟打造完美中文界面

GitHub Desktop中文汉化终极指南:3分钟打造完美中文界面 【免费下载链接】GitHubDesktop2Chinese GithubDesktop语言本地化(汉化)工具 【GitHub桌面客户端中文汉化】 项目地址: https://gitcode.com/gh_mirrors/gi/GitHubDesktop2Chinese 你是否在使用GitHub…

作者头像 李华
网站建设 2026/6/24 2:59:55

从手动分析到智能交易:Chanlun-Pro缠论量化实战指南

从手动分析到智能交易:Chanlun-Pro缠论量化实战指南 【免费下载链接】chanlun-pro 基于缠中说禅所讲缠论理论,以便量化分析市场行情的工具 项目地址: https://gitcode.com/gh_mirrors/ch/chanlun-pro 想象一下,你花了数小时在K线图上手…

作者头像 李华
网站建设 2026/6/24 2:59:41

Vllm 转 Ollama 接口

最新版本VisualStudio已经可以接入其他大语言模型了,通过管理模型的接口进入设置 但是他不支持其他的vllm、llama.cpp接口 而且ollama接口也只支持本地lhttp://localhost:11434,其他不支持好像 到以上位置,这个点击添加按钮没啥用,改地址也…

作者头像 李华
网站建设 2026/6/24 2:59:14

Minecraft世界转换终极指南:如何用Chunker实现跨平台存档共享

Minecraft世界转换终极指南:如何用Chunker实现跨平台存档共享 【免费下载链接】Chunker Convert Minecraft worlds between Java Edition and Bedrock Edition 项目地址: https://gitcode.com/gh_mirrors/chu/Chunker 作为Minecraft玩家,您是否曾…

作者头像 李华