python 远程操作svn

SVN操作脚本

安装模块

pip install pywinrm

脚本如下


#!/usr/bin/env python3
# coding=utf-8
# author:LJX
# describe:仓库授权
# createdate:2021.5.27

import winrm
import json


class SVN(object):
    '''
    # 1、查看winrm服务状态。默认没有启动 winrm enumerate winrm/config/listener
    # 2、启动服务器(网络类型改为专有网络) winrm quickconfig
    # 3、开启防火墙 netsh advfirewall firewall set rule group="Windows 远程管理" new enable=yes
    # 4、启动 winrm quickconfig
    # 5、查看 winrm enumerate winrm/config/listener
    # 5、为winrm service 配置auth winrm set winrm/config/service/auth  @{Basic="true"}
    # 7、为winrm service 配置加密方式为允许非加密 winrm set winrm/config/service  @{AllowUnencrypted="true"}
    '''

    def __init__(self, host, port, user, passwd):
        self.host = host
        self.port = port
        self.user = user
        self.passwd = passwd
        self.winConn = winrm.Session('http://{0}:{1}/wsman'.format(self.host, self.port), auth=(self.user, self.passwd))

    def exec_shell(self, command, msg):
        ret = self.winConn.run_ps(command)
        if ret.status_code == 0:
            print(msg + "成功")
            return ret.std_out.decode()
        elif ret.status_code == 1:
            raise Exception(msg + "失败:" + str(ret.std_err, "utf-8"))

    def parse_data(self, data, isAll=True):
        info_list = []
        if type(data) is list or isAll:
            if isAll:
                if type(data) is list:
                    for info in data:
                        info_list.append(info["Name"])
                    return info_list
                else:
                    return [data["Name"]]
            else:
                return [data["Name"]]
        elif type(data) is dict:
            return True

    def get_SvnUser(self, name=''):
        '''
        获取所有用户
        :return:
        '''
        try:
            data = json.loads(self.exec_shell("Get-SvnLocalUser {0} | ConvertTo-Json".format(name), "查询用户"))
            result = self.parse_data(data, 1 - bool(name))
            return result
        except Exception as e:
            print("用户不存在")
            return []

    def get_SvnGroup(self, name=''):
        '''
        查询用户组
        :return: 用户组列表
        '''
        try:
            data = json.loads(self.exec_shell("""Get-SvnLocalGroup {0}| ConvertTo-Json""".format(name), "查询用户组"))
            result = self.parse_data(data, 1 - bool(name))
            return result
        except Exception as e:
            print("用户组不存在")
            return []

    def get_SvnGroupUser(self, name):
        try:
            data = json.loads(self.exec_shell("Get-SvnLocalGroupMember {0} | ConvertTo-Json".format(name), "用户组中用户查询"))
            result = self.parse_data(data, isAll=True)
            return result
        except Exception as e:
            print("用户组不存在")
            return []

    def get_Repository(self, name=''):
        '''
        查询仓库
        :return:返回仓库列表
        '''
        try:
            data = json.loads(self.exec_shell("""Get-SvnRepository {0}| ConvertTo-Json""".format(name), "查询仓库"))
            result = self.parse_data(data, 1 - bool(name))
            return result
        except Exception as e:
            print("仓库不存在")
            return []

    def add_SvnUser(self, username, password):
        '''
        添加用户
        :param username: 用户名
        :param password: 密码
        :return: 返回true 创建成功 or False 创建失败
        '''
        try:
            if self.get_SvnUser(name=username) == []:
                data = self.exec_shell(
                    '''New-SvnLocalUser -Name {0} -Password (ConvertTo-SecureString -String "{1}" -AsPlainText -Force)'''.format(
                        username, password), "创建用户")
            else:
                if input("用户已存在是否重置密码?Y/N").lower().split(' ') == "Y":
                    data = self.exec_shell(
                        '''Set-SvnLocalUser -Name {0} -Password (ConvertTo-SecureString -String "{1}" -AsPlainText -Force)'''.format(
                            username, password), "重置密码")
            return True
        except Exception as e:
            print(e)

    def add_SvnGroup(self, GroupName):
        '''
        :param GroupName:
        :return: True is successful or False is Fail
        '''
        try:
            if self.get_SvnGroup(GroupName) == []:
                data = self.exec_shell("""New-SvnLocalGroup {0}""".format(GroupName), "用户组添加")
            else:
                print("用户组已存在")
            return True
        except Exception as e:
            print(e)

    def add_UserGroup(self, GroupName, Username):
        try:
            if self.get_SvnGroup(GroupName) != []:
                if username in self.get_SvnGroupUser(GroupName):
                    print("用户已存在组中")
                else:
                    self.exec_shell("Add-SvnLocalGroupMember {0} (Get-SvnLocalUser {1})".format(GroupName, Username),
                                    "用户组添加用户")
            else:
                print("用户组不存在")
            return True
        except Exception as e:
            print("添加失败")

    def add_Repository(self, RepoName):
        '''
        添加仓库
        :param RepoName:
        :return:
        '''
        try:
            if self.get_Repository(RepoName) == []:
                data = self.exec_shell("""New-SvnRepository {0}""".format(RepoName), "仓库添加")
            else:
                print("仓库已存在")
            return True
        except Exception as e:
            print(e)

    def add_GrantUser(self, Repository, username, access):
        '''
        仓库授权用户
        :param Repository
        :param username
        :param access: ReadOnly   NoAccess ReadWrite
        :return: True is successful or False is fail
        '''
        command = """Add-SvnAccessRule -AuthorizationProfile SubversionLocal -Repository {0} -Path /  -AccountName {1} -Access {2} -Force""".format(
            Repository, username, access)
        if self.get_user(username):
            print("用户已存在")
            self.exec_shell(command, "仓库授权")
        else:
            print("用户不存在,创建用户")
            data = self.Add_SvnUser(username)
            if data:
                print("用户创建成功")
                self.exec_shell(command, "仓库授权")
            else:
                print("用户创建失败")

    def add_GrantGroup(self, Repository, GroupName, access):
        '''
        仓库授权用户组
        :param Repository:
        :param GroupName:
        :param access:
        :return: True is successful or False is fail
        '''
        command = '''Add-SvnAccessRule {0} -Path  /  -AccountId "@{1}" -Access {2}'''.format(Repository, GroupName,
                                                                                             access)
        try:
            if self.get_SvnGroup(GroupName):
                self.exec_shell(command, "仓库授权用户组")
            else:
                print("用户不存在,创建用户")
                data = self.add_SvnGroup(GroupName)
                if data:
                    print("用户创建成功")
                    self.exec_shell(command, "仓库授权")
                else:
                    print("用户创建失败")
        except Exception as e:
            print("用户组授权失败")


def createObj():
    svn = SVN(host="ip", port="port", user="user", passwd="password")
    return svn


if __name__ == "__main__":
    svn = createObj()
    params = {
        "Repository": "xxxx",
        "username": "xxxx",
        # 权限分别是access: ReadOnly   NoAccess ReadWrite
        "access": "ReadOnly",
    }
    # 授权仓库用户权限
    data = svn.add_GrantUser(Repository=params["Repository"],username=params["username"],access=params["access"])
    # 授权用户用户组权限
    # data = svn.add_GrantGroup(Repository=params["Repository"],GroupName=params["username"],access=params["access"])
    print(data)
posted @   兰嘉轩  阅读(767)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示