Jenkins的版本是:Jenkins2.138.1

实现的操作接口:

using System;
using System.Collections.Generic; namespace iHRPublish.Utility
{
/// <summary>
/// Jenkins上创建项目
/// </summary>
public interface IJenkinsOperate: IDisposable
{
/// <summary>
/// 构建jenkins项目
/// </summary>
/// <param name="projectName"></param>
/// <returns></returns>
bool BuildJenkinsProject(string projectName);
/// <summary>
/// 在jenkins上创建项目
/// </summary>
/// <param name="projectName">项目名称</param>
/// <param name="info"></param>
/// <returns></returns>
bool CreateJenkinsProject(string projectName, out string info);
/// <summary>
/// 删除jenkins上的项目
/// </summary>
/// <param name="projectName">项目名称</param>
/// <returns></returns>
bool DeleteJenkinsProject(string projectName); /// <summary>
/// Jenkins 项目列表
/// </summary>
/// <returns></returns>
List<JenkinsJobDto> ListJenkinsProject();
/// <summary>
/// 登录
/// </summary>
/// <param name="j_username">jenkins用户名</param>
/// <param name="j_password">jenkins密码</param>
/// <returns></returns>
bool LoginJenkins(string j_username, string j_password);
/// <summary>
/// 重新加载配置文件,用于手动修改项目的config文件后刷新数据用。
/// </summary>
/// <param name="projectName">项目名称</param>
/// <returns></returns>
bool ReloadJenkinsProject(string projectName);
}
}

实现类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web; namespace iHRPublish.Utility
{
/// <summary>
/// Jenkins上创建项目
/// </summary>
public class JenkinsOperate : IJenkinsOperate
{
/// <summary>
/// 写日志
/// </summary>
public static Action<string> writeLogAction;
private static void writeLog(string msg)
{
msg = "[JenkinsOperate]" + msg;
writeLogAction?.Invoke(msg);
Console.WriteLine(msg);
}
static string _j_username = "xxxxx";//这里填入用户名........................................
static string _j_password = "xxxxx";//这里填入密码...............................
static string jenkins_crumb = "568be69f9ad6a3a479c13e71d07b31f7";
static JenkinsOperate()
{
string j_usernameStr = System.Configuration.ConfigurationManager.AppSettings["j_username"];
string j_passwordStr = System.Configuration.ConfigurationManager.AppSettings["j_password"];

string jenkins_crumbStr = System.Configuration.ConfigurationManager.AppSettings["jenkins_crumb"];
_j_username = string.IsNullOrEmpty(j_usernameStr) ? _j_username : j_usernameStr;
_j_password = string.IsNullOrEmpty(j_passwordStr) ? _j_password : j_passwordStr;
//测试用从配置文件读取。
jenkins_crumb = string.IsNullOrEmpty(jenkins_crumbStr) ? jenkins_crumb : jenkins_crumbStr;
}
System.Net.Http.HttpClient client = new HttpClient(); string jenkinsBaseUrl = "http://127.0.0.1:8080/"; /// <summary>
/// Jenkins 操作
/// </summary>
/// <param name="_jenkinsBaseUrl">Jenkins地址,如:http://xxx.xxx.xxx.xxx:8080</param>
public JenkinsOperate(string _jenkinsBaseUrl)
{
string jenkinsBaseUrlStr = System.Configuration.ConfigurationManager.AppSettings["jenkinsBaseUrl"];
jenkinsBaseUrl = string.IsNullOrEmpty(jenkinsBaseUrlStr) ? jenkinsBaseUrl : jenkinsBaseUrlStr;
if (!string.IsNullOrEmpty(_jenkinsBaseUrl))
{
jenkinsBaseUrl = _jenkinsBaseUrl;
}
} /// <summary>
/// 登录
/// </summary>
/// <param name="j_username">jenkins用户名</param>
/// <param name="j_password">jenkins密码</param>
/// <returns></returns>
public bool LoginJenkins(string j_username, string j_password)
{
if (string.IsNullOrEmpty(j_username)) { j_username = _j_username; }
if (string.IsNullOrEmpty(j_password)) { j_password = _j_password; }
string loginUrl = string.Format("{0}/j_acegi_security_check", jenkinsBaseUrl);
object obj = new { j_username = j_username, j_password = j_password };
var objJson = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
List<KeyValuePair<String, String>> loginParamList = new List<KeyValuePair<String, String>>();
loginParamList.Add(new KeyValuePair<string, string>("j_username", j_username));
loginParamList.Add(new KeyValuePair<string, string>("j_password", j_password)); var loginPara = new FormUrlEncodedContent(loginParamList);
var loginResponseMessage = client.PostAsync(loginUrl, loginPara).Result;
var loginStr = loginResponseMessage.Content.ReadAsStringAsync().Result;
writeLog("[loginStr]" + loginStr);
if (loginStr.Contains("登录"))
{
return false;
} //获取Jenkins-Crumb
string jenkinsCrumbStr = "\"Jenkins-Crumb\", \"";
var index = loginStr.IndexOf(jenkinsCrumbStr);
writeLog("[loginStr] jenkinsCrumbStr Index:" + index);
if (index == -)
{
return false;
}
var indexStart = index + jenkinsCrumbStr.Length;
var indexEnd = loginStr.IndexOf("\");", indexStart);
writeLog("[loginStr] jenkinsCrumbStr indexEnd:" + indexEnd);
if (indexEnd == -)
{
return false;
}
string jenkinsCrumb = loginStr.Substring(indexStart, indexEnd - indexStart);
jenkins_crumb = jenkinsCrumb;
return true;
} /// <summary>
/// 在jenkins上创建项目
/// </summary>
/// <param name="projectName">项目名称</param>
/// <param name="info"></param>
/// <returns></returns>
public bool CreateJenkinsProject(string projectName, out string info)
{
info = "ok"; //验证名称
string checkNameUrl = string.Format("{0}/view/all/checkJobName?value={1}", jenkinsBaseUrl, projectName);
var checkResult = client.GetAsync(checkNameUrl).Result;
var checkStr = checkResult.Content.ReadAsStringAsync().Result; writeLog("[CreateJenkinsProject] checkStr:" + checkStr);
if (checkStr != "<div/>")
{
info = "已存在项目名称";
return false;
} //创建新项目
string createItemUrl = string.Format("{0}/view/all/createItem", jenkinsBaseUrl);
List<KeyValuePair<String, String>> createParamList = new List<KeyValuePair<String, String>>();
createParamList.Add(new KeyValuePair<string, string>("name", projectName));
createParamList.Add(new KeyValuePair<string, string>("mode", "hudson.model.FreeStyleProject"));
createParamList.Add(new KeyValuePair<string, string>("from", ""));
createParamList.Add(new KeyValuePair<string, string>("Jenkins-Crumb", jenkins_crumb));
createParamList.Add(new KeyValuePair<string, string>("json", string.Format("{{'name': '{0}', 'mode': 'hudson.model.FreeStyleProject', 'from': '', 'Jenkins-Crumb': '{1}'}}", projectName, jenkins_crumb)));
var createPara = new FormUrlEncodedContent(createParamList);
var createResponseMessage = client.PostAsync(createItemUrl, createPara).Result;
var createStr = createResponseMessage.Content.ReadAsStringAsync().Result; writeLog("[CreateJenkinsProject] createStr:" + createStr);
if (createResponseMessage.StatusCode == HttpStatusCode.OK)
{
return true;
}
return false;
} /// <summary>
/// 删除jenkins上的项目
/// </summary>
/// <param name="projectName">项目名称</param>
/// <returns></returns>
public bool DeleteJenkinsProject(string projectName)
{
//删除
string deleteUrl = string.Format("{0}/job/{1}/doDelete", jenkinsBaseUrl, projectName); List<KeyValuePair<String, String>> deleteParamList = new List<KeyValuePair<String, String>>();
deleteParamList.Add(new KeyValuePair<string, string>("Jenkins-Crumb", jenkins_crumb)); var deletePara = new FormUrlEncodedContent(deleteParamList);
var deleteResponseMessage = client.PostAsync(deleteUrl, deletePara).Result;
var deleteStr = deleteResponseMessage.Content.ReadAsStringAsync().Result; writeLog("[DeleteJenkinsProject] deleteStr:" + deleteStr);
if (deleteResponseMessage.StatusCode == HttpStatusCode.OK)
{
return true;
}
return false;
}
/// <summary>
/// 构建jenkins项目
/// </summary>
/// <param name="projectName"></param>
/// <returns></returns>
public bool BuildJenkinsProject(string projectName)
{
string buildUrl = string.Format("{0}/job/{1}/build?delay=0sec", jenkinsBaseUrl, projectName);
List<KeyValuePair<String, String>> buildParamList = new List<KeyValuePair<String, String>>(); var buildPara = new FormUrlEncodedContent(buildParamList);
client.DefaultRequestHeaders.Add("Jenkins-Crumb", jenkins_crumb);
var buildResponseMessage = client.PostAsync(buildUrl, buildPara).Result;
var buildStr = buildResponseMessage.Content.ReadAsStringAsync().Result;
writeLog("[BuildJenkinsProject] buildStr:" + buildStr);
if (buildResponseMessage.StatusCode == HttpStatusCode.Created)
{
return true;
}
return false;
}
/// <summary>
/// Jenkins 项目列表
/// </summary>
/// <returns></returns>
public List<JenkinsJobDto> ListJenkinsProject()
{
var listUrl = $"{jenkinsBaseUrl}/api/json?pretty=true";
var listResult = client.GetAsync(listUrl).Result;
var listStr = listResult.Content.ReadAsStringAsync().Result;
var jobList = Newtonsoft.Json.JsonConvert.DeserializeObject<JenkinsDto>(listStr);
if (jobList != null && jobList.jobs != null)
{
return jobList.jobs;
}
return new List<JenkinsJobDto>();
}
/// <summary>
/// 重新加载配置文件
/// </summary>
/// <param name="projectName">项目名称</param>
/// <returns></returns>
public bool ReloadJenkinsProject(string projectName)
{
var reloadUrl = $"{jenkinsBaseUrl}/job/{projectName}/reload"; List<KeyValuePair<String, String>> reloadParamList = new List<KeyValuePair<String, String>>();
reloadParamList.Add(new KeyValuePair<string, string>("Jenkins-Crumb", jenkins_crumb)); var reloadPara = new FormUrlEncodedContent(reloadParamList);
var reloadResponseMessage = client.PostAsync(reloadUrl, reloadPara).Result;
var reloadStr = reloadResponseMessage.Content.ReadAsStringAsync().Result; writeLog("[ReloadJenkinsProject] reloadStr:" + reloadStr);
if (reloadResponseMessage.StatusCode == HttpStatusCode.OK)
{
return true;
}
return false;
} /// <summary>
/// 销毁数据
/// </summary>
public void Dispose()
{
client.Dispose();
}
}
}

dto对象:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; namespace iHRPublish.Utility
{
/// <summary>
/// Jenkins job
/// </summary>
public class JenkinsJobDto
{
/// <summary>
/// job类型
/// 如:hudson.model.FreeStyleProject
/// </summary>
public string _class { get; set; }
/// <summary>
/// 项目名称
/// 如:iHR-Hardware-GuangBen
/// </summary>
public string name { get; set; }
/// <summary>
/// jenkins地址
/// 如: http://127.0.0.1:8080/job/iHR-Hardware-GuangBen/
/// </summary>
public string url { get; set; }
/// <summary>
/// 状态
/// 如:notbuilt,blue
/// </summary>
public string color { get; set; }
}
/// <summary>
///
/// </summary>
public class JenkinsDto
{
/// <summary>
/// jobs
/// </summary>
public List<JenkinsJobDto> jobs { get; set; }
}
}

调用方法:

            //在jenkins上创建项目
string jenkinsHost = "http://127.0.0.1:8080";
string jenkinsLoginUserName = "admin";
string jenkinsLoginPwd = "123456";
string projectName = "项目名称";
using (JenkinsOperate jOperate = new JenkinsOperate(dto.jenkinsHost))
{
bool loginSuccess = jOperate.LoginJenkins(jenkinsLoginUserName, jenkinsLoginPwd);
if (!loginSuccess)
{
return ResultHelper.QuickReturnError(false, "Login_Jenkins_Fail", "登录Jenkins失败");
}
string info;
//创建项目
bool createSuccess = jOperate.CreateJenkinsProject(projectName, out info);
if (!createSuccess)
{
return ResultHelper.QuickReturnError(false, "Create_Jenkins_Project_Fail", "创建Jenkins项目失败:" + info);
}
//生成项目

bool createSuccess = jOperate.BuildJenkinsProject(dto.projectName);
                  if (!createSuccess)
                  {
                     return ResultHelper.QuickReturnError(false, "Build_Jenkins_Project_Fail", "创建Jenkins项目失败");
                  }

//列出所有项目
                  var list = jOperate.ListJenkinsProject();
                  if(list == null || list.Count == 0)
                  {
                      return ResultHelper.QuickReturnError<List<JenkinsJobDto>>(null, "Not_Find_Any_Project", "未查询到任何项目");
                  }

//删除项目
                  bool createSuccess = jOperate.DeleteJenkinsProject(projectName);
                  if (!createSuccess)
                  {
                      return ResultHelper.QuickReturnError(false, "Delete_Jenkins_Project_Fail", "删除Jenkins项目失败");
                  }

           }

Jenkins操作,实现增删改查的更多相关文章

  1. 使用python操作XML增删改查

    使用python操作XML增删改查 什么是XML? XML 指可扩展标记语言(EXtensible Markup Language) XML 是一种标记语言,很类似 HTML XML 的设计宗旨是传输 ...

  2. js操作indexedDB增删改查示例

    js操作indexedDB增删改查示例 if ('indexedDB' in window) { // 如果数据库不存在则创建,如果存在但是version更大,会自动升级不会复制原来的版本 var r ...

  3. MySQL数据分析(16)— 数据操作之增删改查

    前面我们说学习MySQL要从三个层面,四大逻辑来学,三个层面就是库层面,表层面和数据层面对吧,数据库里放数据表,表里放数据是吧,大家可以回忆PPT中jacky的这图,我们已经学完了库层面和表层面,从本 ...

  4. Redis简单的数据操作(增删改查)

    #Redis简单的数据操作(增删改查): 字符串类型 string 1. 存储: set key value 127.0.0.1:6379> set username zhangsan OK 2 ...

  5. MongoDB基础入门002--基本操作,增删改查

    一.这里只是演示最基本的操作,更多的信息可以去官网.https://docs.mongodb.com/manual 打开一个cmd,输入mongo命令打开shell,其实这个shell就是mongod ...

  6. 2. MongoDB基本操作 —— 用Mongo.exe操作数据库增删改查

    一.开篇 传统的关系数据库一般由数据库(database).表(table).记录(record)三个层次概念组成,MongoDB是由数据库(database).集合(collection).文档对象 ...

  7. Linq 数据库操作(增删改查)

    Linq数据库增删改查 Linq是一种查询语言,集成包含在formwork中,包含在C#语言中,它的作用是降低查询的门槛,提高开发效率,是我们必须掌握的技术之一,下面是我自己对linq数据库操作的方法 ...

  8. SQLAlchemy表操作和增删改查

    一.SQLAlchemy介绍 SQLAlchemy是一个基于Python实现的ORM框架.该框架建立在 DB API之上,使用关系对象映射进行数据库操作,简言之便是:将类和对象转换成SQL,然后使用数 ...

  9. Django-Model操作数据库(增删改查、连表结构)

    一.数据库操作 1.创建model表         基本结构 1 2 3 4 5 6 from django.db import models     class userinfo(models.M ...

  10. 初次尝试PHP——一个简单的对数据库操作的增删改查例子

    第一次学习PHP,很多人说PHP是最好的语言,学习了一点点,还不敢说这样的话,不过确实蛮好用的. 做了一个简单的对数据库的增删改查的操作,主要是将四种操作写成了独立的函数,之后直接调用函数.以下是代码 ...

随机推荐

  1. Disconf 学习系列之Disconf 的模块架构图

    不多说,直接上干货!  Disconf 的模块架构主要包括: Disconf-Tools . Disconf-Web. Disconf-client 和  Disconf-Core. 每个模块的简单介 ...

  2. javac之Inferring Type Arguments Based on Actual Arguments

    We use the following notational conventions in this section: Type expressions are represented using ...

  3. Scope及其子类介绍

    之前写的文章: 关于作用域范围Scope Scope及相关的子类如下: 同时有些Scope还继承了Scope.ScopeListener类,如下: 1.StarImportScope及ImportSc ...

  4. 理解kubernetes环境的iptables

    node节点的iptables是由kube-proxy生成的,具体实现可以参见kube-proxy的代码 kube-proxy只修改了filter和nat表,它对iptables的链进行了扩充,自定义 ...

  5. Sklearn-RandomForest

    在scikit-learn中,RandomForest的分类类是RandomForestClassifier,回归类是RandomForestRegressor,需要调参的参数包括两部分,第一部分是B ...

  6. chrome 下修改 agent 的方法

    前言 这篇文章和 tiankonguse 的个人网站里的文章保持同步. 很早之前,在 chrome 下修改 agent 的方法是使用 chrome 插件. 后来 chrome 的某一个版本中自带这个功 ...

  7. Vue前端框架面试问题

    1.active-class是哪个组件的属性?嵌套路由怎么定义? 答:vue-router模块的router-link组件. 2.怎么定义vue-router的动态路由?怎么获取传过来的动态参数? 答 ...

  8. Nodejs学习笔记(七)—Node.js + Express 构建网站简单示例

    前言 上一篇学习了一些构建网站会用到的一些知识点:https://www.cnblogs.com/flyingeagle/p/9192936.html 这一篇主要结合前面讲到的知识,去构建一个较为完整 ...

  9. ibatis(sqlmap)中 #与$的使用区别

    在sqlmap文件中不使用“#VALUE#”来原样(参数对应什么类型,就当什么类型,比如拼凑的内容为string则自动加上了‘’)读取,而是$VALUE$方式来读取,即不加任何的东西,比如单引号啥的, ...

  10. import.html 页面导出execl

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...