Beispiel #1
0
    def connect(self):
        ssh = SSHClient()
        config = SSHConfig()
        with open(os.path.expanduser("~/.ssh/config")) as _file:
            config.parse(_file)
        host_config = config.lookup(self.host)
        ssh.set_missing_host_key_policy(AutoAddPolicy())
        ssh.load_system_host_keys()

        ssh.connect(
            self.host,
            username=self.user,
            password=self.password,
            key_filename=host_config["identityfile"][0],
            allow_agent=False,
            timeout=30,
        )
        transport = ssh.get_transport()
        channel = transport.open_session()
        channel.setblocking(1)
        return ssh
Beispiel #2
0
 def run(self, hostname, username, password):
     if self.commands.__len__() == 0: return False
     method = Device.objects.filter(host=hostname)[0].loginmethod
     if method == "ssh":
         ssh = SSHClient()
         ssh.set_missing_host_key_policy(AutoAddPolicy())
         try:
             ssh.connect(hostname=hostname,
                         username=username,
                         password=password,
                         timeout=2)
         except:
             return False
         shell = ssh.invoke_shell()
         shell.send('config terminal' + '\r\n')
         for command in self.commands:
             shell.send(command + '\r\n')
             sleep(0.5)
         return True
     elif method == "telnet":
         pass
Beispiel #3
0
def download():
    remote_folder_name = REMOTE_PATH.split('/')[-1]

    print("INFO - Connecting to Raspberry pi...")
    ssh = SSHClient()
    ssh.set_missing_host_key_policy(AutoAddPolicy())
    ssh.connect(hostname=HOSTNAME, username=USERNAME, password=PASSWORD)

    print("INFO - Downloading {} folder on {}...".format(
        remote_folder_name,
        LOCAL_PATH.split('/')[-1]))
    with SCPClient(ssh.get_transport()) as scp:
        scp.get(remote_path=REMOTE_PATH, local_path=LOCAL_PATH, recursive=True)
        print("DONE - {} downloaded").format(remote_folder_name)

    print("Removing {} folder on raspberry...").format(remote_folder_name)
    with ssh.open_sftp() as sftp:
        rm(sftp, REMOTE_PATH)
        print("DONE - {} folder deleted remotely.").format(remote_folder_name)

    ssh.close()
Beispiel #4
0
 def run(self, cmd):
     log = CommandLog()
     log.server = self.server_object
     ssh = SSHClient()
     ssh.load_system_host_keys(settings.SSH_HOSTKEYS)
     ssh.set_missing_host_key_policy(AutoAddPolicy())
     ssh.connect(self.server_object.domain,
                 username="******",
                 key_filename=settings.SSH_PRIVATEKEY)
     log.command = cmd
     log.execute_user = "******"
     log.save()
     stdin, stdout, stderr = ssh.exec_command(cmd)
     data = {"stdout": stdout.read(), "stderr": stderr.read()}
     log.result_stdout = data.get("stdout")
     log.result_stderr = data.get("stderr")
     log.status_code = stdout.channel.recv_exit_status()
     log.processed = True
     log.save()
     ssh.close()
     return data
 def job(self, run, payload, device):
     ssh_client = SSHClient()
     if run.missing_host_key_policy:
         ssh_client.set_missing_host_key_policy(AutoAddPolicy())
     if run.load_known_host_keys:
         ssh_client.load_system_host_keys()
     source = run.sub(run.source_file, locals())
     destination = run.sub(run.destination_file, locals())
     ssh_client.connect(
         device.ip_address,
         username=device.username,
         password=app.get_password(device.password),
         look_for_keys=run.look_for_keys,
     )
     if run.source_file_includes_globbing:
         glob_source_file_list = glob(source, recursive=False)
         if not glob_source_file_list:
             return {
                 "success": False,
                 "result":
                 f"Glob pattern {source} returned no matching files",
             }
         else:
             files = []
             for glob_source in glob_source_file_list:
                 if Path(glob_source).is_dir():
                     continue
                 _, filename = split(glob_source)
                 if destination[-1] != "/":
                     destination = destination + "/"
                 glob_destination = destination + filename
                 files.append((glob_source, glob_destination))
     else:
         files = [(source, destination)]
     log = ", ".join("Transferring {} to {}".format(*pairs)
                     for pairs in files)
     run.log("info", log, device)
     run.transfer_file(ssh_client, files)
     ssh_client.close()
     return {"success": True, "result": "Transfer successful"}
    def connect(self, ssh=None):
        """Connects the ssh instance.

        If :param:`ssh` is not provided will connect `self.ssh`.
        """
        ssh = ssh if ssh else self.ssh
        ssh.load_system_host_keys()
        if self.trusted_host:
            ssh.set_missing_host_key_policy(AutoAddPolicy())
        while True:
            try:
                ssh.connect(
                    self.hostname,
                    username=self.remote_user,
                    timeout=self.timeout,
                    compress=True,
                )
                print('Connected to host {}. '.format(self.hostname))
                break
            except (socket.timeout, ConnectionRefusedError) as e:
                print('{}. {} for {}@{}. Retrying ...'.format(
                    timezone.now(), str(e), self.remote_user, self.hostname))
                time.sleep(5)
            except AuthenticationException as e:
                raise AuthenticationException('Got {} for user {}@{}'.format(
                    str(e)[0:-1], self.remote_user, self.hostname))
            except BadHostKeyException as e:
                raise BadHostKeyException(
                    'Add server to known_hosts on host {}.'
                    ' Got {}.'.format(e, self.hostname))
            except socket.gaierror:
                raise socket.gaierror(
                    'Hostname {} not known or not available'.format(
                        self.hostname))
            except ConnectionResetError as e:
                raise ConnectionResetError('{} for {}@{}'.format(
                    str(e), self.remote_user, self.hostname))
            except SSHException as e:
                raise SSHException('{} for {}@{}'.format(
                    str(e), self.remote_user, self.hostname))
Beispiel #7
0
 def job(self, payload: dict, device: Device) -> dict:
     ssh_client = SSHClient()
     if self.missing_host_key_policy:
         ssh_client.set_missing_host_key_policy(AutoAddPolicy())
     if self.load_known_host_keys:
         ssh_client.load_system_host_keys()
     source_file = self.sub(self.source_file, locals())
     self.logs.append("Transferring file {source_file} on {device.name}")
     success, result = True, f"File {source_file} transferred successfully"
     ssh_client.connect(
         device.ip_address,
         username=device.username,
         password=device.password,
         look_for_keys=self.look_for_keys,
     )
     source = self.sub(self.source_file, locals())
     destination = self.sub(self.destination_file, locals())
     if self.source_file_includes_globbing:
         glob_source_file_list = glob(source, recursive=False)
         if not glob_source_file_list:
             success = False
             result = f"Glob pattern {source} returned no matching files"
         else:
             pairs = []
             for glob_source in glob_source_file_list:
                 path, filename = split(glob_source)
                 if destination[-1] != "/":
                     destination = destination + "/"
                 glob_destination = destination + filename
                 pairs.append((glob_source, glob_destination))
             info(f"Preparing to transfer glob file {glob_source}")
             self.transfer_file(ssh_client, pairs)
     else:
         self.transfer_file(
             ssh_client,
             self.sub(self.source_file, locals()),
             self.sub(self.destination_file, locals()),
         )
     ssh_client.close()
     return {"success": success, "result": result}
Beispiel #8
0
def main(target_type: str):

    if target_type == LIVE_TYPE:
        creds = live_credentials
        PATH_TO_FILES = LIVE_PATH_TO_FILES
    else:
        creds = editorial_credentials
        PATH_TO_FILES = EDITORIAL_PATH_TO_FILES

    ssh_client = SSHClient()
    try:
        ssh_client.set_missing_host_key_policy(AutoAddPolicy())
        ssh_client.connect(
            hostname=creds.host,
            port=creds.port,
            username=creds.user,
            password=creds.password,
        )

        ftp_client = ssh_client.open_sftp()
        for server_path in creds.paths:
            for filename in FILENAMES:
                file_path = PATH_TO_FILES / filename
                if not file_path.is_file():
                    logging.info(f'{file_path} is not a file. Skipping.')
                    continue
                ftp_client.put(file_path, server_path + '/' + filename)
        ftp_client.close()

        stdin, stdout, stderr = ssh_client.exec_command(CMD)
        out = stdout.readlines()
        if out:
            logging.info(*out)

        errors = stderr.readlines()
        if errors:
            logging.error(*errors)

    finally:
        ssh_client.close()
Beispiel #9
0
    def connect(self):
        logger.debug(
            "Opening SSH connection to {host}:{port}".format(
                host=self.host, port=self.port))
        client = SSHClient()
        client.load_system_host_keys()
        client.set_missing_host_key_policy(AutoAddPolicy())

        try:
            client.connect(
                self.host,
                port=self.port,
                username=self.username,
                timeout=self.timeout, )
        except ValueError as e:
            logger.error(e)
            logger.warning(
                """
Patching Crypto.Cipher.AES.new and making another attempt.

See here for the details:
http://uucode.com/blog/2015/02/20/workaround-for-ctr-mode-needs-counter-parameter-not-iv/
            """)
            client.close()
            import Crypto.Cipher.AES
            orig_new = Crypto.Cipher.AES.new

            def fixed_AES_new(key, *ls):
                if Crypto.Cipher.AES.MODE_CTR == ls[0]:
                    ls = list(ls)
                    ls[1] = ''
                return orig_new(key, *ls)

            Crypto.Cipher.AES.new = fixed_AES_new
            client.connect(
                self.host,
                port=self.port,
                username=self.username,
                timeout=self.timeout, )
        return client
Beispiel #10
0
def get_router():
    response = {}
    for router in request.json["routers"]:
        try:
            ssh = SSHClient()
            ssh.set_missing_host_key_policy(AutoAddPolicy())
            ssh.connect(router["ip"], router["port"], router["user"],
                        router["password"])
        except Exception:
            response[router["ip"] + "_" +
                     router["interface"]] = "Connection error"
            ssh.close()
        else:
            ssh_command = ssh.invoke_shell()
            ssh_command.send("show interface {}\n".format(router["interface"]))
            time.sleep(2)
            output = ssh_command.recv(5000).decode()
            # Validate if interface exist
            if output.find("Invalid input detected at") < 0:
                extract_data = {}
                if "bandwidth" in request.json["info"]:
                    search = re.search(r'BW (.*?), ', output)
                    if search:
                        extract_data["bandwidth"] = search.group(1)
                    else:
                        extract_data["bandwidth"] = "bandwidth not found"
                if "address" in request.json["info"]:
                    search = re.search(r'Internet address is (.*?)\r\n',
                                       output)
                    if search:
                        extract_data["address"] = search.group(1)
                    else:
                        extract_data["address"] = "address not found"
                response[router["ip"] + "_" +
                         router["interface"]] = extract_data
            else:
                key = router["ip"] + "_" + router["interface"]
                response[key] = "Interface not found"
            ssh.close()
    return response
Beispiel #11
0
    def __init__(self, ssh_config):
        """Instantiate a SSH client and connect to a microVM."""
        self.netns_file_path = ssh_config['netns_file_path']
        self.ssh_client = SSHClient()  # pylint: disable=no-value-for-parameter
        self.ssh_client.set_missing_host_key_policy(AutoAddPolicy())
        assert os.path.exists(ssh_config['ssh_key_path'])

        # Retry to connect to the host as long as the delay between calls
        # is less than 30 seconds. Sleep 1, 2, 4, 8, ... seconds between
        # attempts. These parameters might need additional tweaking when we
        # add tests with 1000 Firecracker microvm.

        # TODO: If a microvm runs in a particular network namespace, we have to
        # temporarily switch to that namespace when doing something that routes
        # packets over the network, otherwise the destination will not be
        # reachable. Use a better setup/solution at some point!

        if self.netns_file_path:
            with Namespace(self.netns_file_path, 'net'):
                self.initial_connect(ssh_config)
        else:
            self.initial_connect(ssh_config)
Beispiel #12
0
 def start_session(self, server, username='', password='', timeout=15):
     """
     This method is used to start a new connection to server.
     :param
         server: The remote server in order to initiate ssh connection with
         username: Remote server username
         password: Remote server password
         timeout: Timeout while trying to connect [s]
     """
     try:
         client = SSHClient()
         client.set_missing_host_key_policy(AutoAddPolicy())
         client.connect(server,
                        username=username,
                        password=password,
                        timeout=timeout)
         self.set_client(client)
         return True
     except error as e:
         print("opening session error")
         self._error = e
         return False
Beispiel #13
0
    def __init__(self,
                 host,
                 port,
                 user,
                 passwd,
                 retries=60,
                 delay=10,
                 log_lvl=logging.DEBUG,
                 keyPairFiles=None,
                 timeout=10.0):
        self.host = None
        self.port = 22
        self.user = user
        self.passwd = passwd
        self.keyPairFiles = keyPairFiles
        self.ssh = SSHClient()
        self.ssh.set_missing_host_key_policy(AutoAddPolicy())
        self.logger = logging.getLogger('sshClient')
        self.retryCnt = 0
        self.delay = 0
        self.timeout = 3.0
        ch = logging.StreamHandler()
        ch.setLevel(log_lvl)
        self.logger.addHandler(ch)

        # Check invalid host value and raise exception
        # Atleast host is required for connection
        if host is not None and host != '':
            self.host = host
        if retries is not None and retries > 0:
            self.retryCnt = retries
        if delay is not None and delay > 0:
            self.delay = delay
        if timeout is not None and timeout > 0:
            self.timeout = timeout
        if port is not None and port >= 0:
            self.port = port
        if self.createConnection() == FAILED:
            raise internalError("SSH Connection Failed")
Beispiel #14
0
def _connect_via_jump_box(server: str) -> SSHClient:
    ssh = SSHClient()
    ssh.load_system_host_keys()
    ssh.set_missing_host_key_policy(AutoAddPolicy())

    try:
        """
        This is SSH pivoting it ssh to host Y via host X, can be used due to different networks
        We doing direct-tcpip channel and pasing it as socket to be used
        """
        if jumpbox_used and JUMP_BOX_USERNAME:
            jumpbox_transport = jumpbox.get_transport()
            src_addr = (JUMP_BOX, JUMP_BOX_PORT)
            dest_addr = (server, JUMP_BOX_PORT)
            jumpbox_channel = jumpbox_transport.open_channel("direct-tcpip", dest_addr, src_addr)

            ssh.connect(server, username=REMOTE_SERVER_USER, look_for_keys=True, allow_agent=True, sock=jumpbox_channel)
        else:
            ssh.connect(server, username=REMOTE_SERVER_USER, look_for_keys=True, allow_agent=True)
    except BadHostKeyException as e:
        sys.exit(str(e))
    return ssh
Beispiel #15
0
def test():


    #scp pi@[172.21.39.116]:/home/pi/camera/A.jpg /Users/yasu

    HOST = '172.21.39.116'
    PORT = "22"
    USER = '******'
    PSWD = '0000'

    ssh = SSHClient()
    ssh.set_missing_host_key_policy(AutoAddPolicy())
    ssh.connect(HOST, port=PORT,username=USER, password=PSWD)

    scp = SCPClient(ssh.get_transport())
    scp.get('/home/pi/camera/roomA309.jpg')

    path1='/Users/yasu/darknet/'
    #copy roomA309.jpg to ./room
    shutil.copyfile(path1 + 'roomA309.jpg', path1 + '/room/roomA309.jpg')

    os.remove(path1 + 'roomA309.jpg')
Beispiel #16
0
def oxe_update_ccca_cfg_dev_all_in_one(host, port, password, api_server):
    """Summary
    
    Args:
        host (TYPE): Description
        port (TYPE): Description
        password (TYPE): Description
        api_server (TYPE): Description
    """
    # update ccca.cfg for all-in-one connection
    client = SSHClient()  # use the paramiko SSHClient
    client.set_missing_host_key_policy(
        AutoAddPolicy())  # automatically add SSH key
    try:
        client.connect(host, port, username='******', password=password)
    except AuthenticationException:
        print('*** Failed to connect to {}:{}'.format(host, port))
    command = "cat >> /usr3/mao/ccca.cfg << EOF\nRAINBOW_HOST={}\nEOF\n".format(
        api_server)
    # print(command)
    client.exec_command(command)
    client.close()
Beispiel #17
0
def create_worker(host):
    config = SSHConfig()
    proxy = None
    if os.path.exists(os.path.expanduser("~/.ssh/config")):
        config.parse(open(os.path.expanduser("~/.ssh/config")))
        if host.hostname is not None and "proxycommand" in config.lookup(
                host.hostname):
            proxy = ProxyCommand(config.lookup(host.hostname)["proxycommand"])

    # proxy = paramiko.ProxyCommand("ssh -o StrictHostKeyChecking=no [email protected] nc 118.138.239.241 22")

    worker = SSHClient()
    worker.load_system_host_keys()
    worker.set_missing_host_key_policy(AutoAddPolicy())

    worker.hostname = (
        host.hostname
    )  # store all this for later reference (e.g., logging, reconnection)
    worker.username = host.username
    worker.password = host.password
    worker.proxy = proxy
    if not host.key_filename is None:
        worker.pkey = RSAKey.from_private_key_file(host.key_filename,
                                                   host.key_password)
    else:
        worker.pkey = None

    # time.sleep(4)
    # worker.connect(hostname=host.hostname, username=host.username, password=host.password, key_filename=host.key_filename, sock=proxy, timeout=3600)

    worker.connect(
        hostname=host.hostname,
        username=host.username,
        password=host.password,
        pkey=worker.pkey,
        sock=proxy,
    )

    return worker
Beispiel #18
0
def get_service_status(hostname, servicename):
    ssh_client = SSHClient()
    ssh_client.set_missing_host_key_policy(AutoAddPolicy())
    ssh_config = SSHConfig()
    config_file = path.expanduser("~/.ssh/config")
    if path.exists(config_file):
        config_file_opened = open(config_file)
        ssh_config.parse(config_file_opened)

    server_config = ssh_config.lookup(hostname)
    ssh_client.connect(hostname=server_config['hostname'],
                       username=server_config['user'],
                       port=server_config['port'],
                       key_filename=server_config['identityfile'])

    stdin, stdout, stderr = ssh_client.exec_command(
        "sudo service {} status | grep 'Active'".format(servicename))
    stdout_file = stdout.read()
    status_line = stdout_file.decode()
    status = status_line.split()[1]
    ssh_client.close()
    return status
Beispiel #19
0
    def forward(self, host, user=None, password=None, port=22):

        self._proxy = SSHClient()
        user = user or self.user
        password = password or self.password

        self._proxy.set_missing_host_key_policy(AutoAddPolicy())

        try:
            self._proxy.connect(host,
                                port=port,
                                username=user,
                                password=password)
        except ssh_exception.AuthenticationException:
            print("Error: Authentication failed for user {0}".format(
                self.user))
            exit(-1)

        transport = self._proxy.get_transport()
        self.proxy = transport.open_channel("direct-tcpip",
                                            (self.host, self.port),
                                            (host, port))
Beispiel #20
0
def get_ssh(host, user, password, look_for_keys=True):
    ssh = SSHClient()
    ssh.set_missing_host_key_policy(AutoAddPolicy())
    try:
        try:
            ssh.connect(host,
                        username=user,
                        password=password,
                        timeout=5,
                        look_for_keys=look_for_keys)
        except AuthenticationException as err:
            LOG.error("{0} for host={1} username={2} password={3}".format(
                repr(err), host, user, password))
            raise
        except Exception as e:
            LOG.error(str(e))
            if 'timed out' in str(e) or 'Connection refused' in str(e):
                raise Exception('Connection error: timed out or refused.')
            raise e
        yield ssh
    finally:
        ssh.close()
Beispiel #21
0
 def __connect(self):
     """
     Open connection to remote host.
     """
     try:
         self.client = SSHClient()
         self.client.load_system_host_keys()
         self.client.set_missing_host_key_policy(AutoAddPolicy())
         self.client.connect(self.host,
                             username=self.user,
                             key_filename=self.ssh_key_filepath,
                             look_for_keys=True,
                             timeout=5000)
         self.scp = SCPClient(self.client.get_transport())
     except AuthenticationException as error:
         logger.info(
             'Authentication failed: did you remember to create an SSH key?'
         )
         logger.error(error)
         raise error
     finally:
         return self.client
Beispiel #22
0
def get_paramiko_ssh(location, **kwargs):
    from paramiko import AutoAddPolicy
    from plumbum.machines.paramiko_machine import ParamikoMachine

    password = location.facts.get('password')
    keyfile = location.facts.get('keyfile')
    settings = {
        'user': location.facts.get('user', 'root'),
        'port': location.facts.get('port', 22),
        'look_for_keys': False,
        'missing_host_policy': AutoAddPolicy(),
        'keep_alive': 60
    }

    if password:
        settings['password'] = password
    if keyfile:
        settings['keyfile'] = keyfile

    ssh = ParamikoMachine(location.hostname, **settings)
    ssh.sftp.walk = types.MethodType(walk, ssh.sftp)
    return ssh
Beispiel #23
0
	def revoke_one_server(self, server, userhost, key_rsa, userName, usermail, port):
		"""
		Delete a heimdall replication.
		"""
		client = SSHClient()
		client.load_system_host_keys()
		client.set_missing_host_key_policy(AutoAddPolicy())
		client.connect('%s' % server, port=port, username=userhost)

		# ## Insert permission into server authorized_keys ssh file
		sshconfig_file = "~/.ssh/authorized_keys"
		rsa_search = str(key_rsa).replace('\r\n', '').replace('\r', '').replace('\n', '')

		stdin, stdout, stderr = client.exec_command("grep -v '%s' %s > %s.tmp" % (rsa_search, sshconfig_file, sshconfig_file))
		stdin, stdout, stderr = client.exec_command("cat %s > %s.bak" % (sshconfig_file, sshconfig_file))
		stdin, stdout, stderr = client.exec_command("chmod 0600 %s.tmp" % (sshconfig_file))
		#stdin, stdout, stderr = client.exec_command("rm %s" % (sshconfig_file))
		stdin, stdout, stderr = client.exec_command("mv %s.tmp %s" % (sshconfig_file, sshconfig_file))
		stdin, stdout, stderr = client.exec_command("rm %s.bak" % (sshconfig_file))
		logger.info("Access revoked")
		client.close()
		self.notify(server, userName, userhost, True, usermail)
Beispiel #24
0
    def __init__(self, hostname, port=22, username=None, config_path=None):
        self.hostname = hostname
        self.client = SSHClient()

        self.client.load_system_host_keys()
        self.client.set_missing_host_key_policy(AutoAddPolicy())

        if config_path is None:
            config_path = os.path.join(os.path.expanduser('~'), '.ssh', 'config')
        self.config = SSHConfig()
        with open(config_path) as config_file:
            self.config.parse(config_file)

        if hostname in self.config.get_hostnames():
            host_cfg = self.config.lookup(hostname)
            full_hostname = host_cfg.get('hostname', hostname)
            if username is None:
                username = host_cfg.get('user', None)  # If none, it will try the user running the server.
        else:
            full_hostname = hostname

        self.client.connect(full_hostname, port, username=username)
Beispiel #25
0
 def connect(self):
     # this reduces the timeout of SSHClient's connect()
     # for failed dns lookups
     try:
         self.host_check(self.host)
     except Exception as e:
         # todo logging e
         print('[-] CONNECTION FAILED', self.host)
         return None
     try:
         s = SSHClient()
         s.set_missing_host_key_policy(AutoAddPolicy())
         if self.password:
             s.connect(self.host, port=22, username=self.user,
                       password=self.password, timeout=1)
         else:
             s.connect(self.host, port=22, username=self.user,
                       timeout=1, pkey=self.key)
         return s
     except Exception as e:
         # todo logging e
         print('[-] CONNECTION FAILED:', self.host)
Beispiel #26
0
 def connection(self):
     """Open SSH connection to remote host."""
     try:
         client = SSHClient()
         client.load_system_host_keys()
         client.set_missing_host_key_policy(AutoAddPolicy())
         client.connect(
             self.host,
             username=self.user,
             password=self.password,
             key_filename=self.ssh_key_filepath,
             timeout=5000,
         )
         return client
     except AuthenticationException as e:
         LOGGER.error(
             f"AuthenticationException occurred; did you remember to generate an SSH key? {e}"
         )
         raise e
     except Exception as e:
         LOGGER.error(f"Unexpected error occurred: {e}")
         raise e
Beispiel #27
0
 def test_server(self, ip, port, username, password):
     try:
         sleep(2)
         _ip = ip or self.ip
         _port = port or self.port
         _username = username or self.username
         _password = password or self.password
         ssh = SSHClient()
         ssh.set_missing_host_key_policy(AutoAddPolicy(
         ))  #if you have default ones, remove them before using this..
         ssh.connect(_ip,
                     port=_port,
                     username=_username,
                     password=_password)
     except Exception as e:
         self.logs.error([
             "errors", {
                 'server': 'ssh_server',
                 'error': 'write',
                 "type": "error -> " + repr(e)
             }
         ])
Beispiel #28
0
def ssh_exec(cmd,
             ip,
             username=DEFAULT_CVM_USERNAME,
             password=DEFAULT_CVM_PASSWD,
             timeout=10,
             verbose=False):
    """Executes the cmd on remote host"""
    if not username:
        username = DEFAULT_CVM_USERNAME
    if not password:
        password = DEFAULT_CVM_PASSWD
    ssh = SSHClient()
    ssh.set_missing_host_key_policy(AutoAddPolicy())
    ssh.connect(ip, username=username, password=password, timeout=10)
    pad = ' ' * (len(ip) + 5)
    if verbose:
        print textwrap.fill("%s >>> %s" % (ip, cmd),
                            width=80,
                            initial_indent='',
                            subsequent_indent=pad)
    ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(cmd, timeout=timeout)
    rv = ssh_stdout.channel.recv_exit_status()
    output = ssh_stdout.readlines() if rv == 0 else None
    stderr = ssh_stderr.readlines()
    ssh.close()
    if verbose:
        print textwrap.fill("%s <<< RV: %s" % (ip, rv),
                            width=80,
                            initial_indent='',
                            subsequent_indent=pad)
        print textwrap.fill("STDOUT: %s" % output,
                            width=80,
                            initial_indent=pad,
                            subsequent_indent=pad + (' ' * 8))
        print textwrap.fill("STDERR: %s" % stderr,
                            width=80,
                            initial_indent=pad,
                            subsequent_indent=pad + (' ' * 8))
    return {'rv': rv, 'stdout': output, 'stderr': stderr}
Beispiel #29
0
def upload_file(server, localpath, remotepath, user=None, password=None):
    """
    Upload a file to remote server

    Args:
        server (str): Name of the server to upload
        localpath (str): Local file to upload
        remotepath (str): Target path on the remote server. filename should be included
        user (str): User to use for the remote connection

    """
    if not user:
        user = '******'

    ssh = SSHClient()
    ssh.set_missing_host_key_policy(AutoAddPolicy())
    ssh.connect(hostname=server, username=user, password=password)
    sftp = ssh.open_sftp()
    log.info(f"uploading {localpath} to {user}@{server}:{remotepath}")
    sftp.put(localpath, remotepath)
    sftp.close()
    ssh.close()
Beispiel #30
0
 def retrieve_backup(self, backup_name=None):
     if not backup_name:
         logging.warning('Tried to obtain a backup but no name was given')
         return False
     out = []
     if 'port' in self.connection:
         ssh_port = self.connection['port']
     else:
         ssh_port = 22
     ssh = SSHClient()
     ssh.set_missing_host_key_policy(AutoAddPolicy())
     ssh.load_host_keys(
         filename=path.join(path.expanduser('~'), '.ssh', 'known_hosts'))
     try:
         ssh.connect(hostname=self.connection['host'],
                     username=self.connection['user'],
                     port=ssh_port,
                     key_filename=self.connection['keyfile'])
     except SSHException as e:
         logging.critical('SSH Failed: {}'.format(e))
         ssh.close()
         return False
     try:
         ftp = ssh.open_sftp()
         ftp.chdir(self.remote_path + '/' + backup_name)
         data = ftp.listdir()
         if not path.isdir('/app/backups/' + backup_name):
             mkdir('/app/backups/' + backup_name)
         for to_retrieve in data:
             logging.warning('Retrieving {} from backup {}'.format(
                 to_retrieve, '/app/backups/' + backup_name))
             ftp.get(to_retrieve,
                     '/app/backups/' + backup_name + '/' + to_retrieve)
     except SSHException as e:
         logging.critical('SSH error: {}'.format(e))
         return False
     except FileNotFoundError:
         out = 'Backup not found in remote server'
     return out