首页 .Net dotnet项目执行shell脚本实现简单的自动化部署

dotnet项目执行shell脚本实现简单的自动化部署

不要k8s、不要docker、不要Jenkins,只要一个部署脚本,只是一个小项目单台服务器,实现提交代码自动执行脚本,拉代码构建部署项目。

创建一个web api 项目,作为webhook,实现接收web请求后执行shell脚本

项目代码:

  1. using Microsoft.AspNetCore.Mvc;

  2. using Microsoft.Extensions.Logging;

  3. using System;

  4. using System.Diagnostics;


  5. namespace ShellHandler.Controllers

  6. {

  7.    [ApiController]

  8.    [Route("[controller]")]

  9.    public class HandlerController : ControllerBase

  10.    {

  11.        private readonly ILogger<HandlerController> _logger;


  12.        public HandlerController(ILogger<HandlerController> logger)

  13.        {

  14.            _logger = logger;

  15.        }


  16.        [HttpPost]

  17.        public string Execute(string fileName)

  18.        {

  19.            try

  20.            {

  21.                var processStartInfo = new ProcessStartInfo($"./{fileName}") { RedirectStandardOutput = true };

  22.                var process = Process.Start(processStartInfo);

  23.                if (process == null)

  24.                {

  25.                    Console.WriteLine("Can not run shell .");

  26.                }

  27.                else

  28.                {

  29.                    using (var sr = process.StandardOutput)

  30.                    {

  31.                        while (!sr.EndOfStream)

  32.                        {

  33.                            var str = sr.ReadLine();

  34.                            Console.WriteLine(str);

  35.                        }


  36.                        if (!process.HasExited)

  37.                        {

  38.                            process.Kill();

  39.                        }

  40.                    }

  41.                }

  42.                return "ok";


  43.            }

  44.            catch (Exception ex)

  45.            {

  46.                _logger.LogInformation(ex.Message);

  47.                return ex.Message;

  48.            }

  49.        }

  50.    }

  51. }

在服务器部署当前项目

nohup dotnet ShellHandler.dll --urls http://0.0.0.0:8080 &

在项目根目录创建部署脚本publish.sh

#!/bin/bash#杀死占用8081端口的进程kill -9 $(lsof -i:8081 -t)cd /home/web/web-demo/#拉取代码git pull#发布项目到publish文件夹dotnet publish -o publishcd publish/#后台运行项目nohup dotnet WebDemo.dll --urls http://0.0.0.0:8081 &

添加执行权限

chmod a+x publish.sh

创建一个Demo项目部署到服务器,托管到gitee

把webhook地址添加到gitee的WebHooks,并指定脚本文件名项目

出处:https://www.tnblog.net/17801418352/article/details/6382


特别声明:本站部分内容收集于互联网是出于更直观传递信息的目的。该内容版权归原作者所有,并不代表本站赞同其观点和对其真实性负责。如该内容涉及任何第三方合法权利,请及时与824310991@qq.com联系,我们会及时反馈并处理完毕。