Best Python code snippet using autotest_python
sftp.py
Source:sftp.py  
1#!/usr/bin/python32#3# SPDX-License-Identifier: Apache-2.04#5import getpass6import os7import time8import subprocess9import paramiko10from utils.install_log import LOG11def sftp_send(source, remote_host, remote_port, destination, username, password):12    """13    Send files to remote server14    """15    LOG.info("Connecting to server %s with username %s", remote_host, username)16    ssh_client = paramiko.SSHClient()17    ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())18    ## TODO(WEI): need to make this timeout handling better19    retry = 020    while retry < 8:21        try:22            ssh_client.connect(remote_host, port=remote_port,23                               username=username, password=password,24                               look_for_keys=False, allow_agent=False)25            sftp_client = ssh_client.open_sftp()26            retry = 827        except Exception as e:28            LOG.info("******* try again")29            retry += 130            time.sleep(10)31    LOG.info("Sending file from %s to %s", source, destination)32    sftp_client.put(source, destination)33    LOG.info("Done")34    sftp_client.close()35    ssh_client.close()36def send_dir(source, remote_host, remote_port, destination, username,37             password, follow_links=True, clear_known_hosts=True):38    # Only works from linux for now39    if not source.endswith('/') or not source.endswith('\\'):40        source = source + '/'41    params = {42        'source': source,43        'remote_host': remote_host,44        'destination': destination,45        'port': remote_port,46        'username': username,47        'password': password,48        'follow_links': "L" if follow_links else "",49        }50    if clear_known_hosts:51        if remote_host == '127.0.0.1':52            keygen_arg = "[127.0.0.1]:{}".format(remote_port)53        else:54            keygen_arg = remote_host55        cmd = 'ssh-keygen -f "/home/%s/.ssh/known_hosts" -R' \56              ' %s', getpass.getuser(), keygen_arg57        LOG.info("CMD: %s", cmd)58        process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)59        for line in iter(process.stdout.readline, b''):60            LOG.info("%s", line.decode("utf-8").strip())61        process.wait()62    LOG.info("Running rsync of dir: {source} ->"  \63             "{username}@{remote_host}:{destination}".format(**params))64    cmd = ("rsync -av{follow_links} "65           "--rsh=\"/usr/bin/sshpass -p {password} ssh -p {port} -o StrictHostKeyChecking=no -l {username}\" "66           "{source}* {username}@{remote_host}:{destination}".format(**params))67    LOG.info("CMD: %s", cmd)68    process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)69    for line in iter(process.stdout.readline, b''):70        LOG.info("%s", line.decode("utf-8").strip())71    process.wait()72    if process.returncode:73        raise Exception("Error in rsync, return code:{}".format(process.returncode))74def send_dir_fallback(source, remote_host, destination, username, password):75    """76    Send directory contents to remote server, usually controller-077    Note: does not send nested directories only files.78    args:79    - source: full path to directory80    e.g. /localhost/loadbuild/jenkins/latest_build/81    - Remote host: name of host to log into, controller-0 by default82    e.g. myhost.com83    - destination: where to store the file on host: /home/myuser/84    """85    LOG.info("Connecting to server %s with username %s", remote_host, username)86    ssh_client = paramiko.SSHClient()87    ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())88    ssh_client.connect(remote_host, username=username, password=password, look_for_keys=False, allow_agent=False)89    sftp_client = ssh_client.open_sftp()90    path = ''91    send_img = False92    for items in os.listdir(source):93        path = source+items94        if os.path.isfile(path):95            if items.endswith('.img'):96                remote_path = destination+'images/'+items97                LOG.info("Sending file from %s to %s", path, remote_path)98                sftp_client.put(path, remote_path)99                send_img = True100            elif items.endswith('.iso'):101                pass102            else:103                remote_path = destination+items104                LOG.info("Sending file from %s to %s", path, remote_path)105                sftp_client.put(path, remote_path)106    LOG.info("Done")107    sftp_client.close()108    ssh_client.close()109    if send_img:...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
