ceph 对象存储 创建api
admin
2023-07-15 18:22:03
0次
# -*- coding:utf-8 -*-

import boto
import boto.s3.connection
import paramiko

class Accountinfo():
    """
    用法详见 http://docs.ceph.org.cn/man/8/radosgw-admin/
    """
    def __init__(self):
        self.hostname = '192.168.44.70'
        self.port = 22
        self.username = 'root'
        self.passwd = '123456'

    def new_connect(self):
        try:
            paramiko.util.log_to_file('paramiko.log')
            ssh = paramiko.SSHClient()
            ssh.load_system_host_keys()
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            ssh.connect(hostname='192.168.44.70',port=22,username='root',password='123456')
            return ssh

        except Exception as e:
            return 'error'

    def user_manager(self,username,flag):
        """
        为s3访问创建radosgw用户
        flag: c -> create,d -> delete
        """
        ssh = self.new_connect()
        if not isinstance(ssh,str):
            c_command = '/usr/bin/radosgw-admin  user create --uid="%s" --display-name="%s"' % (username, username.title())
            d_command = '/usr/bin/radosgw-admin  user rm --uid="%s"' % (username)

            if flag == 'c':
                stdin, stdout, stderr = ssh.exec_command(c_command)
                outstr = stdout.read()
                errstr = stdout.read()
                ssh.close()
                return outstr,errstr
            elif flag == 'd':
                stdin, stdout, stderr = ssh.exec_command(d_command)
                ssh.close()
                return 'delete %s success'% username
                # return stdout, stderr
            else:
                ssh.close()
                return 'flag == c or d','flag error'

        return 'connect error'

class CephS3():

    # 单例模式

    __instance = None

    def __init__(self):
        self.access_key = "BKOLF8C5319QK2UIMQ09"
        self.secret_key = "jBiFwY3LeHh78tM9W6Y8oQUM2VNIbieGVViB3wEB"
        self.host = '192.168.44.70'
        self.port = 7480
        self.conn = boto.connect_s3(
            aws_access_key_id= self.access_key,
            aws_secret_access_key= self.secret_key,
            host = self.host,
            port = self.port,
            is_secure=False,
            calling_format = boto.s3.connection.OrdinaryCallingFormat()
        )

    @staticmethod
    def get_connect():

        if CephS3.__instance:
            return CephS3.__instance
        else:
            CephS3.__instance = CephS3().conn
            return CephS3.__instance

    def list_all_buckets(self):
        con = CephS3.get_connect()
        all_buckets = con.get_all_buckets()

        for bucket in all_buckets:
            print("{name}\t{created}".format(name=bucket.name,created=bucket.creation_date))

    def create_bucket(self,bucketname):
        # con = self.connect()
        con = CephS3.get_connect()
        all_bucket = con.get_all_buckets()
        all_bucket_name = [i.name for i in all_bucket]

        try:
            if bucketname not in all_bucket_name:
                bucket = con.create_bucket(bucketname)
                return 'ok'
                # print('Bucket %s create success'% bucketname)
            else:
                return 'fail'
                # print('Bucket %s already exists!' % bucketname)
        except Exception as e:
            return str(e)

    def delete_bucket(self,bucketname):

        con = CephS3.get_connect()
        all_bucket = con.get_all_buckets()
        all_bucket_name = [i.name for i in all_bucket]

        try:
            if bucketname in all_bucket_name:
                bucket = con.delete_bucket(bucketname)
                return 'ok'

            else:
                return 'fail'

        except Exception as e:
            print(str(e))

    def list_bucket_object(self,bucketname):

        con = CephS3.get_connect()
        bucket = con.get_bucket(bucketname)
        list_buckets = bucket.list()

        print("%-10s\t%-10s\t%-10s\n"%('Name','Size','Modified'))
        for key in list_buckets:
            print("{name:<10}\t{size:<10}\t{modified:<10}".format(name=key.name,size=key.size,modified=key.last_modified))

    def create_object(self,bucketname,obj_key,obj_value):
        """新建一个内容是字符串 obj_value 的文件 obj_key"""

        con = CephS3.get_connect()
        bucket = con.get_bucket(bucketname)
        list_buckets = bucket.list()
        obj_keys = [i.name for i in list_buckets]
        try:
            if obj_key not in obj_keys:
                bucket_key = bucket.new_key(obj_key)
                bucket_key.set_contents_from_string(obj_value)
                return 'ok'
            return 'exists'
        except Exception as e:
            return str(e)

    def modifi_object_acl(self,bucketname,obj_key,acl='public-read'):
        """
        修改对象的权限
        :param bucketname:
        :param obj_key:
        :param acl: public-read 公开可读   private 私有
        :return:
        """
        # con = self.connect()
        con = CephS3.get_connect()
        bucket = con.get_bucket(bucketname)
        try:
            bucket_key = bucket.get_key(obj_key)
            bucket_key.set_canned_acl(acl)
            return 'ok'
        except Exception as e:
            return str(e)

    def make_obj_url(self,bucketname,obj_key,sign=False):
        try:

            con = CephS3.get_connect()
            bucket = con.get_bucket(bucketname)
            key = bucket.get_key(obj_key)
            if not sign:
                key_url_no_sign = key.generate_url(0,query_auth=False,force_http=True)
                return key_url_no_sign
            key_url_sign = key.generate_url(3600,query_auth=True,force_http=True)
            return key_url_sign
        except Exception as e:
            return str(e)

    def download_to_file(self,bucketname,obj_key,dest_file):
        try:
            # con = self.connect()
            con = CephS3.get_connect()
            bucket = con.get_bucket(bucketname)
            key = bucket.get_key(obj_key)
            key.get_contents_to_filename(dest_file)
            return 'ok'
        except Exception as e:
            return str(e)

    def delete_bucket_key(self,bucketname,obj_key):
        try:
            # con = self.connect()
            con = CephS3.get_connect()
            bucket = con.get_bucket(bucketname)
            bucket.delete_key(obj_key)
            return 'ok'
        except Exception as e:
            return str(e)

if __name__ == '__main__':
    cephapi = CephS3()

    url = cephapi.make_obj_url('bucket_bamboo','haproxy.txt',True)
    print(url)

    # cephapi.list_bucket_object('bucket_bamboo')

    # 创建用户 获取keys 信息

    # um = Accountinfo()
    # out, err = um.user_manager('wuye','c')
    #
    # if type(out) == str:
    #     res = json.loads(out)
    #     print(json.dumps(res["keys"][0],indent=2))
    # else:
    #     print(out,err)

相关内容

热门资讯

空调连续工作多久需要停机休息 空调连续工作的时间取决于多个因素,包括空调的型号、功率、使用环境和维护情况等。一般来说,空调可以连续...
空调哪个符号是除湿的 空调除湿功能通常用一个水滴形状的符号表示。不同品牌和型号的空调遥控器可能会有所差异,但一般来说,除湿...
格力空调多长时间加一次氟利昂 1、一般情况下,空调对氟利昂的使用量是非常小的,所以在空调使用了四年左右的时候再考虑加也没问题。2、...
空调用多长时间需要加氟一次 一般情况下是五年。当出现以下这几种情况时,空调才需要加氟。1、空调的室内机和室外机各有两个接口,当接...
格调生活·C标思享荟:卡萨帝在... 9月12日的郑州龙湖金融岛,夜风轻拂,灯光璀璨。“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑...
品牌价值破千亿、高端份额持续领... 9月12日,“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑州站”在郑州龙湖金融岛举办。2026...
空调主板坏了修800还是换新的 空调主板坏了是修还是换新,需要考虑多个因素,以下是一些建议:1. 维修成本:如果维修费用较低,比如 ...
空调开多久需要休息多长时间 问题:空调开多久需要休息多长时间回答:1、在使用空调的过程中,一般空调开7~8个小时左右需要休息2~...
中央空调多长时间清洗一次 1、一般空调开机前清洗一次即可,空调开机中间时段再清洗一次,空调关机时清洗一次,这样比较合理。2、空...
中央空调氟利昂多久加一次 看空调制热和制冷程度,很多人的观点认为氟利昂必须一年放一次,其实这个观点是错误的,理解上面有点偏差,...