Beispiel #1
0
    def handle_noargs(self, **options):
        disk = YaDisk(settings.DUMP_ACCOUNT_NAME, settings.DUMP_PASSWORD)

        def save_mkdir(dir):
            try:
                disk.mkdir(dir)
            except YaDiskException:
                pass

        now = datetime.now()
        save_mkdir('Backup')
        save_mkdir('Backup/db')
        save_mkdir('Backup/db/%s' % now.strftime('%Y_%m'))

        dump_filename = '%s_backup_%s.sql' % (settings.DATABASES['default']['NAME'], now.strftime('%Y%m%d_%H%M'))
        tmp_filename = dump_filename + '.gz'
        tmp = open(tmp_filename, 'wb')

        dump = check_output([
            'mysqldump',
            '--user='******'default']['USER'],
            '--password='******'default']['PASSWORD'],
            '--host=' + settings.DATABASES['default']['HOST'],
            settings.DATABASES['default']['NAME'],
        ])

        archive = zipfile.ZipFile(tmp, 'w', zipfile.ZIP_DEFLATED)
        archive.writestr(dump_filename, dump)
        archive.close()

        tmp.close()

        disk.upload(tmp_filename, 'Backup/db/%s/%s' % (now.strftime('%Y_%m'), tmp_filename))

        os.remove(tmp_filename)
Beispiel #2
0
def Auth_user():
    try:
        f = open(getcwd() + '/Info/file.txt', 'r+')
    except FileNotFoundError:
        mkdir(getcwd() + '/Info')
        f = open(getcwd() + '/Info/file.txt', 'w+')
        login = input('Информация о пользователе не найдена\n'
                      'Авторизация Нового Пользователя\n'
                      'Login:'******'\n'
        password = input('Password:'******'/Info/Users.txt'
    disk = YaDisk(input('Ya_Login:'******'Ya_Password:'******'Logs/Users.txt', path)
    g = open(path, 'r')
    s = g.read()
    g.close()
    if s != (login + '\n' + password):
        print('Такого пользователя в базе данных нет, exit')
        exit()
    #remove(path)
    print('\nВыполняется вход...\n')
    time.sleep(1)
    user_login = f.readline().replace('Login:'******'')
    print('Добро пожаловать ', user_login)
    print('Для справки пропишите .help\n'
          'Для выхода из программы, используйте exit')
    f.close()
    return user_login, disk
Beispiel #3
0
 def __init__(self):
     self.path_main = "TelegramBOT"
     self.disk = YaDisk(config.DISK_LOGIN, config.DISK_PASSWORD_APP)
     elements = self.disk.ls("/")
     for element in elements:
         if element['isDir'] and element['displayname'] == self.path_main:
             return
     self.disk.mkdir(self.path_main)
Beispiel #4
0
def upload(_login, _password, _server_dir, _file):
    if os.path.isfile(_file):
        disk = YaDisk(_login, _password)
        disk.upload(_file, _server_dir + '/' + os.path.basename(_file))
        link = disk.publish_doc(_server_dir + '/' + os.path.basename(_file))
        print link
    else:
        print "Error: file-path is bad"
        return 1
Beispiel #5
0
    def __init__(self, src_file_csv, ya_dir):
        self.src_file_csv = src_file_csv
        self.ya_dir = ya_dir

        self.ya = YaDisk(conf['ya']['login'], conf['ya']['pass'])
        self.certs = {
            c['displayname'].split(".")[0]: c['path']
            for c in self.ya.ls('/{}'.format(ya_dir))
        }
class YandexDiskClass:
    def __init__(self):
        self.path_main = "TelegramCouponBOT"
        self.disk = YaDisk(config.DISK_LOGIN, config.DISK_PASSWORD_APP)
        elements = self.disk.ls("/")
        for element in elements:
            if element['isDir'] and element['displayname'] == self.path_main:
                return
        self.disk.mkdir(self.path_main)

    def get_user(self, userID):
        try:
            return self.disk.ls(f"{self.path_main}/{userID}")
        except:
            return None

    def mkdir_user(self, userID):
        try:
            self.disk.mkdir(f"{self.path_main}/{userID}")
        except:
            print(
                f"YandexDisk Error: <{userID}> Данный пользователь уже создан")

    def add_file(self, userID, file):
        if not self.get_user(userID):
            self.mkdir_user(userID)
        elements_path = file.split('/')
        file_name = elements_path[len(elements_path) - 1]
        self.disk.upload(file, f"/{self.path_main}/{userID}/{file_name}")
 def upload_yandex_disk(self):
     disk = YaDisk(self.Ylogin, self.Ypassword)
     print('{0}video.mp4'.format(self.videofolder))
     disk.mkdir('Videos/{0}/{1}'.format(self.game, self.timestamp))
     disk.upload(
         '{0}video.mp4'.format(self.videofolder),
         'Videos/{0}/{1}/video.mp4'.format(self.game, self.timestamp))
     disk.upload(
         '{0}hashtags.txt'.format(self.videofolder),
         'Videos/{0}/{1}/hashtags.txt'.format(self.game, self.timestamp))
     disk.upload(
         '{0}link_to_original.txt'.format(self.videofolder),
         'Videos/{0}/{1}/link_to_original.txt'.format(
             self.game, self.timestamp))
     return
class YaBackup(object):
    """
    Main object to work with backups
    TODO: backup Media folder as a single option    
    """
    DATETIME_FORMAT = settings.YABACKUP_SETTINGS['DATE_TIME_FORMAT']
    disk = YaDisk(settings.YABACKUP_SETTINGS['YADISK_LOGIN'],
                  settings.YABACKUP_SETTINGS['YADISK_PASSWORD'])

    def run_backups(self, queryset=None, manual=False):
        """        
        Main function to run backups (manual or ron based)
        """
        if manual:
            backup_list = queryset
        else:
            backup_list = Backup.objects.all()

        for backup in backup_list:
            # Add a slash to output directory path if it's not there and create this folder
            output_directory = os.path.join(backup.output_directory, '')
            if not os.path.exists(output_directory):
                os.mkdir(output_directory)
                print('Root folder created: ', output_directory)

            backup_date = datetime.datetime.now().strftime(
                self.DATETIME_FORMAT + '_')
            file_name = output_directory + backup_date + backup.file_name
            paths_list = backup.paths.all()
            zip_file = zipfile.ZipFile(file_name,
                                       'w',
                                       compression=zipfile.ZIP_DEFLATED)

            for path in paths_list:
                if os.path.exists(path.path):
                    utilities = ZipUtilities()
                    utilities.zip(path.path, zip_file)
                else:
                    print("File or folder doesn't exist: ", path)

            if backup.mysqldump:
                utilities = DatabaseUtilities()
                utilities.dump(output_directory, zip_file)

            zip_file.close()

            if backup.upload:
                self.disk.upload(
                    file_name,
                    settings.YABACKUP_SETTINGS['YADISK_BACKUP_ROOT'] +
                    backup_date + backup.file_name)
                print(file_name, ' successfully uploaded')

                if backup.delete_after_upload:
                    os.remove(file_name)
                    print(file_name, ' was removed')
Beispiel #9
0
    def setUpClass(cls):
        cls.disk = YaDisk(LOGIN, PASSWORD)
        # take any file in work directory
        for item in os.listdir('.'):
            if os.path.isfile(item):
                cls.remote_file = item
                break

        cls.remote_folder = '/TestYaDisk_{}'.format(''.join(
            random.choice(string.ascii_uppercase) for _ in range(6)))
        cls.remote_path = "{folder}/{file}".format(folder=cls.remote_folder,
                                                   file=cls.remote_file)
Beispiel #10
0
    def handle_noargs(self, **options):
        disk = YaDisk(settings.DUMP_ACCOUNT_NAME, settings.DUMP_PASSWORD)

        def save_mkdir(dir):
            try:
                disk.mkdir(dir)
            except YaDiskException:
                pass

        now = datetime.now()
        save_mkdir('Backup')
        save_mkdir('Backup/db')
        save_mkdir('Backup/db/%s' % now.strftime('%Y_%m'))

        dump_filename = '%s_backup_%s.sql' % (
            settings.DATABASES['default']['NAME'], now.strftime('%Y%m%d_%H%M'))
        tmp_filename = dump_filename + '.gz'
        tmp = open(tmp_filename, 'wb')

        dump = check_output([
            'mysqldump',
            '--user='******'default']['USER'],
            '--password='******'default']['PASSWORD'],
            '--host=' + settings.DATABASES['default']['HOST'],
            settings.DATABASES['default']['NAME'],
        ])

        archive = zipfile.ZipFile(tmp, 'w', zipfile.ZIP_DEFLATED)
        archive.writestr(dump_filename, dump)
        archive.close()

        tmp.close()

        disk.upload(tmp_filename,
                    'Backup/db/%s/%s' % (now.strftime('%Y_%m'), tmp_filename))

        os.remove(tmp_filename)
Beispiel #11
0
class YandexDiskClass:
    def __init__(self):
        self.path_main = "TelegramBOT"
        self.disk = YaDisk(config.DISK_LOGIN, config.DISK_PASSWORD_APP)
        elements = self.disk.ls("/")
        for element in elements:
            if element['isDir'] and element['displayname'] == self.path_main:
                return
        self.disk.mkdir(self.path_main)

    def get_departments(self):
        return self.disk.ls(self.path_main)

    def get_department(self, departmentName):
        try:
            return self.disk.ls(f"{self.path_main}/{departmentName}")
        except:
            return None

    def get_staffer(self, stafferID, departmentName):
        try:
            return self.disk.ls(
                f"{self.path_main}/{departmentName}/{stafferID}")
        except:
            return None

    def get_order_staffer(self, orderID, stafferID, departmentName):
        try:
            return self.disk.ls(
                f"{self.path_main}/{departmentName}/{stafferID}/{orderID}")
        except:
            return None

    def mkdir_department(self, departmentName):
        try:
            self.disk.mkdir(f"{self.path_main}/{departmentName}")
        except:
            print(
                f"YandexDisk Error: <{departmentName}> Данный отдел уже создан"
            )

    def mkdir_staffer(self, stafferID, departmentName):
        try:
            if self.get_department(departmentName):
                self.disk.mkdir(
                    f"{self.path_main}/{departmentName}/{stafferID}")
            else:
                print(
                    f"YandexDisk Error: <{departmentName}> Данный отдел не создан"
                )
        except:
            print(
                f"YandexDisk Error: <{stafferID}> Данный сотрудник уже добавлен в <{departmentName}>"
            )

    def mkdir_order(self, orderID, stafferID, departmentName):
        try:
            if self.get_staffer(stafferID, departmentName):
                self.disk.mkdir(
                    f"{self.path_main}/{departmentName}/{stafferID}/{orderID}")
            else:
                print(
                    f"YandexDisk Error: В <{departmentName}> этом отделе нет сотрудника <{stafferID}>"
                )
        except:
            print(
                f"YandexDisk Error: <{orderID}> Данный заказ уже добавлен сотруднику <{stafferID}> отдела <{departmentName}>"
            )

    def rename_department(self, departmentNameOld, departmentNameNew):
        try:
            self.disk.mkdir(f"/{self.path_main}/{departmentNameNew}/")
        except:
            print(
                f"YandexDisk Error: <{departmentNameNew}> Данный отдел уже создан"
            )
            return
        self.disk.cp(f"/{self.path_main}/{departmentNameOld}/",
                     f"/{self.path_main}/{departmentNameNew}/")
        time.sleep(2)
        self.disk.rm(f"{self.path_main}/{departmentNameOld}")

    def add_file(self, stafferID, departmentName, orderID, file):
        if not self.get_department(departmentName):
            self.mkdir_department(departmentName)
        if not self.get_staffer(stafferID, departmentName):
            self.mkdir_staffer(stafferID, departmentName)
        if not self.get_order_staffer(orderID, stafferID, departmentName):
            self.mkdir_order(orderID, stafferID, departmentName)
        elements_path = file.split('/')
        file_name = elements_path[len(elements_path) - 1]
        self.disk.upload(
            file,
            f"/{self.path_main}/{departmentName}/{stafferID}/{orderID}/{file_name}"
        )
Beispiel #12
0
# Save PID to pid file
pid = str(os.getpid())
logging.info("PID is {}".format(pid))
if sett['pidfile']:
    with open(sett['pidfile'], "w") as f:
        f.write(pid)

# Set up relays
rs = RelaySet(sett)

# Set up camera
camera = PiCamera(resolution=(2592, 1944))
time.sleep(2)

# Set Up YaDisk webdav
disk = YaDisk(sett['yandex']['login'], sett['yandex']['pass'])

while True:
    rs.actualize()
    photo_path = make_photo()
    photo_name = photo_path.split("/")[-1]
    ya_path = "asparagus/%s" % photo_name
    if photo_path:
        try:
            rotate_photo(photo_path)
            disk.upload(photo_path, ya_path)
        except:
            logging.info('Could not upload photo')
            pass
    else:
        logging.info('Could not capture photo')
URL = 'https://freezone.name/ajax/update-software-version'
YaDiskDir = '/Miner'

parser = argparse.ArgumentParser()
parser.add_argument('--secret',
                    help='Secret token for server software version update')
parser.add_argument('--login', help='YaDisk login')
parser.add_argument('--password', help='YaDisk password')
parser.add_argument('--soft_version', help='Software version')
parser.add_argument('--base_dir', required=True, help='Base directory')
args = parser.parse_args()
BASE = args.base_dir
print(f'BASE DIR: "{BASE}"')

disk = YaDisk(args.login, args.password)
exe_file = None
for f in glob.glob(BASE + '\*.exe'):
    exe_file = f

if exe_file:
    deployed_exes = [
        x['path'] for x in disk.ls(YaDiskDir) if x['path'][-4:] == '.exe'
    ]
    src = os.path.realpath(exe_file)
    dst = YaDiskDir + '/' + os.path.basename(exe_file)
    disk.upload(src, dst)
    try:
        public_url = disk.publish(dst)
        resp = requests.post(
            URL,
Beispiel #14
0
 def test_bad_auth(self):
     try:
         YaDisk(None, None)
     except YaDiskException as e:
         self.assertTrue(str(e).startswith(str(e.code)))
Beispiel #15
0
from YaDiskClient.YaDiskClient import YaDisk

login = ''
password = ''

disk = YaDisk(login, password)

print(disk.ls('/'))
disk.upload('example.py', 'example.py')
    return text


path = '.'
if (len(sys.argv) > 1):
    path = os.path.abspath(sys.argv[1])

memberonly = False
if (len(sys.argv) > 2):
    memberonly = len(sys.argv[2]) > 0

user = '******'
if (len(sys.argv) > 3):
    user = sys.argv[3]

yadisk = YaDisk(os.getenv('YALOGIN'), os.getenv('YAPASSWD'))

for root, dirs, files in os.walk(path, topdown=False):

    cwd = os.getcwd()
    os.chdir(root)

    for name in files:

        fname, ext = os.path.splitext(name)

        if ext.lower() in (
                '.gif',
                '.jpg',
                '.png',
        ):
Beispiel #17
0
for line in logins:
    line = line.split(' ')
    line[1] = line[1].strip("\n").strip(' ')
    if 'insta_user' in line:
        insta_user = line[1]
    if 'insta_psw' in line:
        insta_psw = line[1]
    if 'yadisk_user' in line:
        yadisk_user = line[1]
    if 'yadisk_psw' in line:
        yadisk_psw = line[1]
logins.close()

InstagramAPI = InstagramAPI(insta_user, insta_psw)
InstagramAPI.login()
disk = YaDisk(yadisk_user, yadisk_psw)


def sendVideo(videoFile, thumb):
    InstagramAPI.uploadVideo(videoFile, thumb, caption="Tortuguero")
    try:
        disk.ls(videoPath)
    except:
        print('exc')
        disk.mkdir(videoPath)
        print('video-bt created')
    i = 0
    while True:
        if "video" + str(i) + ".mp4" in str(disk.ls(videoPath)):
            print('video', "video" + str(i) + ".mp4", 'detekt')
        else:
Beispiel #18
0
class CertPublisher:
    def __init__(self, src_file_csv, ya_dir):
        self.src_file_csv = src_file_csv
        self.ya_dir = ya_dir

        self.ya = YaDisk(conf['ya']['login'], conf['ya']['pass'])
        self.certs = {
            c['displayname'].split(".")[0]: c['path']
            for c in self.ya.ls('/{}'.format(ya_dir))
        }

    def share_cert_for(self, name):
        retries = 0
        while retries <= 5:
            retries += 1
            try:
                cert = self.certs[name]
                return self.ya.publish(cert)
            except Exception as e:
                click.echo(repr(e))
                sleep(1)
        return "###"

    def process_one(self, client, clients_processed):
        name, mail = client[:2]
        name = self._normalize_name(name)
        mail = self._normalize_mail(mail)
        ref = self.share_cert_for(name)
        res = (name.strip(), mail, ref)
        click.echo(res)
        clients_processed.append(res)

    def publish(self):
        # Read & schedule
        executor = ThreadPoolExecutor(max_workers=10)
        tasks = []
        clients_processed = []
        with open(self.src_file_csv) as inp:
            reader = csv.reader(inp, delimiter=',')
            for client in reader:
                tasks.append(
                    executor.submit(self.process_one, client,
                                    clients_processed))
        # Execute
        wait(tasks)
        click.echo("Processed {} certs".format(len(tasks)))
        # Write out
        out_path = os.path.join(
            os.path.dirname(self.src_file_csv),
            os.path.basename(self.src_file_csv).split(".")[0] + "_done.csv")
        with open(out_path, "w") as out:
            writer = csv.writer(out, delimiter=',')
            for p in clients_processed:
                writer.writerow(p)
        return out_path

    def _normalize_name(self, name):
        name = name.strip("'")
        name = name.strip()
        #name = name.split()
        #name = " ".join(part for part in name if part)
        return name

    def _normalize_mail(self, mail):
        mail = mail.strip("'")
        mail = mail.strip()
        return mail
Beispiel #19
0
from YaDiskClient.YaDiskClient import YaDisk
import os
import sys

f_accounts = open('acc.txt','r')
acc_arr = [account for account in f_accounts]
f_accounts.close()
files_arr = os.listdir('.')
f_urls = open('urls.txt','w')
for files in files_arr:
    for account in acc_arr:
        email = account.split(':')[0]
        password = account.replace('\n','').split(':')[1]
        disk = YaDisk(email, password)
        disk.df()
        if files == 'urls.txt' or files == os.path.basename(__file__) or files == 'acc.txt':
            continue
        print(os.path.join(os.path.dirname(os.path.abspath(__file__)),files) + ' ---> ' + files)
        disk.upload(os.path.join(os.path.dirname(os.path.abspath(__file__)),files), files)
        shared_url = disk.publish('/' + files)
        f_urls.write('{} -->  Filename : {} -->  Shared Url : {}\n'.format(email,files,shared_url))
f_urls.close()
sys.exit()
Beispiel #20
0
path_backup = config['path_backup']
path_webdav = config['path_webdav']
path_backup_today = path_backup + date_today_str + "/"
path_webdav_today = path_webdav + date_today_str + "/"
backup_sys = config['backup']['sys']
backup_db = config['backup']['db']
backup_files = config['backup']['files']
exclude = config['exclude']
remove_old_logs = config['remove_old_logs']
store_old = config['store_old']
sleep_time = 2  # кол-во секунд, на которое время от времени засыпать...

config_f.close()
######### <<

disk = YaDisk(yd_u, yd_p)  # Подключаемся к ЯДиску

######### >> Создаем директорию для сегодняшнего бэкапа
if not os.path.exists(path_backup_today):
    try:
        os.makedirs(path_backup_today)
    except BaseException:
        print('Dir ' + path_backup_today + ' already exists')

os.chdir(path_backup_today)  # переходим в директорию с бекапами
######### <<

######### >> Создаём директорию для бекапа на ЯДиске
try_ = True
try_i = 1
Beispiel #21
0
path_webdav = config['path_webdav']
path_backup_today = path_backup + date_today_str +"/"
path_webdav_today = path_webdav + date_today_str +"/"
backup_sys = config['backup']['sys']
backup_db = config['backup']['db']
backup_files = config['backup']['files']
exclude = config['exclude']
remove_old_logs = config['remove_old_logs']
store_old = config['store_old']
sleep_time = 2 # кол-во секунд, на которое время от времени засыпать...

config_f.close()
######### <<


disk = YaDisk( yd_u, yd_p ) # Подключаемся к ЯДиску


######### >> Создаем директорию для сегодняшнего бэкапа
if not os.path.exists( path_backup_today ):
	try:
		os.makedirs( path_backup_today )
	except BaseException:
		print( 'Dir '+ path_backup_today +' already exists' )

os.chdir( path_backup_today ) # переходим в директорию с бекапами
######### <<

######### >> Создаём директорию для бекапа на ЯДиске
try_ = True
try_i = 1
Beispiel #22
0
def make_connection(username, password):
    return YaDisk(username, password)