def _get_connection(self, host): """ Setup a connection for running commands on remote host. """ ssh_options = None conn = SSHConnection() ssh_config = self.get_store("ssh_config") if ssh_config is not None: conn.temp_file = tempfile.NamedTemporaryFile() conn.temp_file.write(ssh_config.encode('utf-8')) conn.temp_file.flush() # make visible to other processes ssh_config_fname = conn.temp_file.name else: ssh_config_fname = self.get_localized_module_option( "ssh_config_file") if ssh_config_fname: if not os.path.isfile(ssh_config_fname): raise Exception("ssh_config \"{}\" does not exist".format( ssh_config_fname)) ssh_options = "-F {}".format(ssh_config_fname) self.log.info("opening connection to host '{}' with ssh " "options '{}'".format(host, ssh_options)) conn.conn = remoto.Connection(host, logger=self.log, detect_sudo=True, ssh_options=ssh_options) conn.conn.import_module(remotes) return conn
def get_connection(hostname, username=None, threads=5, use_sudo=None, detect_sudo=True, **kw): """ A very simple helper, meant to return a connection that will know about the need to use sudo. """ if kw.get('logger') is False: # explicitly disable remote logging remote_logger = None else: remote_logger = logging.getLogger(hostname) if username: hostname = "%s@%s" % (username, hostname) if ceph_medic.config.get('ssh_config'): hostname = "-F %s %s" % (ceph_medic.config.get('ssh_config'), hostname) try: conn = remoto.Connection( hostname, logger=remote_logger, threads=threads, detect_sudo=detect_sudo, ) # Set a timeout value in seconds to disconnect and move on # if no data is sent back. conn.global_timeout = 300 # XXX put this somewhere else if not ceph_medic.config['cluster_name']: cluster_conf_files, stderr, exit_code = remoto.process.check( conn, ['ls', '/etc/ceph/']) cluster_name = 'ceph' if 'ceph.conf' not in cluster_conf_files: logger.warning( '/etc/ceph/ceph.conf was not found, will try to infer the cluster name' ) for i in cluster_conf_files: if i.endswith('conf'): cluster_name = i.split('.conf')[0] logger.warning('inferred %s as the cluster name', cluster_name) ceph_medic.metadata['cluster_name'] = cluster_name else: ceph_medic.metadata['cluster_name'] = ceph_medic.config[ 'cluster_name'] return conn except Exception as error: msg = "connecting to host: %s " % hostname errors = "resulted in errors: %s %s" % (error.__class__.__name__, error) logger.error(msg) logger.error(errors) raise error
def _get_connection(self, host): """ Setup a connection for running commands on remote host. """ self.log.info("opening connection to host '{}' with ssh " "options '{}'".format(host, self._ssh_options)) conn = remoto.Connection('root@' + host, logger=self.log, ssh_options=self._ssh_options) conn.import_module(remotes) return conn
def _get_connection(self, host): """ Setup a connection for running commands on remote host. """ n = self.ssh_user + '@' + host self.log.info("Opening connection to {} with ssh options '{}'".format( n, self._ssh_options)) conn = remoto.Connection(n, logger=self.log.getChild(n), ssh_options=self._ssh_options) conn.import_module(remotes) return conn
def _build_conn(hostname, loggername, silent, ssh_configpath=None): '''Returns a remoto-wrapped execnet connection. Warning: The `remoto.Connection` objects created here must be properly closed. Args: hostname (str): Remote host (or ip) to connect to. silent (bool): If set, the connection is as silent as possible. Only stderr prints are logged (`logging.ERROR` level). loggername (str): If `silent` is set, sets quiet logger to have given name. This is useful for when you want to change the log level later. ssh_configpath (optional str): If set, sets execnet ssh config parameters to given path. This way, we can change ssh-based connection behaviour. Returns: configured `remoto.Connection` object on success, `None` on failure.''' logging.basicConfig() logger = logging.getLogger(loggername) logger.setLevel(logging.ERROR if silent else logging.DEBUG) kwargs = dict() kwargs['logger'] = logger if ssh_configpath: kwargs['ssh_options'] = '-F {}'.format(ssh_configpath) try: return remoto.Connection(hostname, **kwargs) except Exception as e: printe('Could not connect to remote host {}'.format(hostname)) return None
# https://pypi.org/project/remoto/ import remoto from remoto.process import check, run conn = remoto.Connection('localhost') print(check(conn, ['ls', '/nonexistent/path'])) conn = remoto.connection.get('ssh')('localhost') print(check(conn, ['sh', '-c', 'source ~/.bashrc'])) run(conn, ['whoami'])