正确写法

import jenkins

class JenkinsServer:
    _instance = None
    serverUrl = "http://192.168.100.101:8081"
    username = "admin"
    password = "api token授权令牌 不是密码"

    def __new__(cls):
        if not cls._instance:
            cls._instance = super().__new__(cls)
            cls._instance.server = jenkins.Jenkins(cls.serverUrl, cls.username, cls.password)
        return cls._instance

    def __getattr__(self, attr):
        return getattr(self._instance.server, attr)

server = JenkinsServer()
defProjectName = "jenkinsfile-gen-template"
def create_a_job(newProjectName,scriptPath):
   if server.job_exists(newProjectName) == True :
      print("项目已存在,删除后重新创建!")
      server.delete_job(newProjectName)
   config_xml=server.get_job_config(defProjectName)
   new_config_xml = config_xml.replace("<scriptPath>devops/kjgh-test/web-KjghReact.groovy</scriptPath>","<scriptPath>{}</scriptPath>".format(scriptPath))
   print(new_config_xml)
   server.create_job(newProjectName,new_config_xml)

def build_a_job(projectName):
    if server.job_exists(projectName) == True :
        server.build_job(projectName)
    else:
        print("项目不存在!")

获取API Token

Python-Jenkins教程:python调用jenkins创建job和触发构建完整代码_Jenkins

错误示范

下述代码不能保证server是单例的,每次请求都会创建一个实例

创建job

import jenkins

#login
serverUrl = "http://192.168.100.101:8081"
username = "admin"
password = "api token授权令牌 不是密码"
server = jenkins.Jenkins(serverUrl,username,password)

defProjectName = "jenkinsfile-gen-template"
def create_a_job(newProjectName,scriptPath):
   if server.job_exists(newProjectName) == True :
      print("项目已存在,删除后重新创建!")
      server.delete_job(newProjectName)
   config_xml=server.get_job_config(defProjectName)
   new_config_xml = config_xml.replace("<scriptPath>devops/kjgh-test/web-KjghReact.groovy</scriptPath>","<scriptPath>{}</scriptPath>".format(scriptPath))
   print(new_config_xml)
   server.create_job(newProjectName,new_config_xml)

触发构建

import jenkins

# if __name__ == '__main__':
#login
serverUrl = "http://192.168.100.101:8081"
username = "admin"
password = "api token授权令牌 不是密码"
server = jenkins.Jenkins(serverUrl,username,password)

def build_a_job(projectName):
    if server.job_exists(projectName) == True :
        server.build_job(projectName)
    else:
        print("项目不存在!")