Esempio n. 1
0
    def connect_to(self, user, host, command):

        while True:
            print("connecting to %s (%i/10)" % (host, self.i))

            try:
                client = paramiko.SSHClient()
                client._policy = paramiko.WarningPolicy()
                client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

                ssh_config = paramiko.SSHConfig()
                user_config_file = os.path.expanduser("~/.ssh/config")
                if os.path.exists(user_config_file):
                    with open(user_config_file) as f:
                        ssh_config.parse(f)

                cfg = {'hostname': host, 'username': user}

                user_config = ssh_config.lookup(cfg['hostname'])
                for k in ('hostname', 'username', 'port'):
                    if k in user_config:
                        cfg[k] = user_config[k]

                if 'proxycommand' in user_config:
                    cfg['sock'] = paramiko.ProxyCommand(
                        user_config['proxycommand'])

                client.connect(**cfg)
                # execute command
                stdin, stdout, stderr = client.exec_command(command)
                out = stdout.read().decode('utf-8')
                err = stderr.read().decode('utf-8')
                #print('OUT:'+out+' ERR:'+err)

                if not out:
                    print(colors.red('STDERR: ' + err))
                else:
                    print(colors.green('STDOUT: ' + out))

                break
            except paramiko.AuthenticationException:
                print("Authentication failed when connecting to %s" % host)
                sys.exit(1)
            except:
                print("Could not SSH to %s, waiting for it to start" % host)
                self.i += 1
                time.sleep(2)

            # If we could not connect within time limit
            if self.i == 10:
                print
                "Could not connect to %s. Giving up" % host
                sys.exit(1)
Esempio n. 2
0
    def gethostconfig(self, file, host):
        file = os.path.expanduser(file)
        if not os.path.isfile(file):
            return {}

        sshconfig = paramiko.SSHConfig()
        try:
            sshconfig.parse(open(file))
        except Exception as e:
            raise BackendException(u"could not load '%s', maybe corrupt?" % (file))

        return sshconfig.lookup(host)
Esempio n. 3
0
    def __init__(
        self,
        remote_host,
        remote_port,
        username=None,
        password=None,
        key_file=None,
        key_string=None,
        timeout=10,
        keepalive_interval=30,
        compress=True,
        no_host_key_check=True,
        allow_host_key_change=False,
        logger=None,
    ):
        self.remote_host = check.str_param(remote_host, 'remote_host')
        self.remote_port = check.opt_int_param(remote_port, 'remote_port')
        self.username = check.opt_str_param(username, 'username')
        self.password = check.opt_str_param(password, 'password')
        self.key_file = check.opt_str_param(key_file, 'key_file')
        self.timeout = check.opt_int_param(timeout, 'timeout')
        self.keepalive_interval = check.opt_int_param(keepalive_interval, 'keepalive_interval')
        self.compress = check.opt_bool_param(compress, 'compress')
        self.no_host_key_check = check.opt_bool_param(no_host_key_check, 'no_host_key_check')
        self.allow_host_key_change = check.opt_bool_param(
            allow_host_key_change, 'allow_host_key_change'
        )
        self.log = logger

        self.host_proxy = None

        # Create RSAKey object from private key string
        self.key_obj = key_from_str(key_string) if key_string is not None else None

        # Auto detecting username values from system
        if not self.username:
            logger.debug(
                'username to ssh to host: %s is not specified. Using system\'s default provided by'
                ' getpass.getuser()' % self.remote_host
            )
            self.username = getpass.getuser()

        user_ssh_config_filename = os.path.expanduser('~/.ssh/config')
        if os.path.isfile(user_ssh_config_filename):
            ssh_conf = paramiko.SSHConfig()
            ssh_conf.parse(open(user_ssh_config_filename))
            host_info = ssh_conf.lookup(self.remote_host)
            if host_info and host_info.get('proxycommand'):
                self.host_proxy = paramiko.ProxyCommand(host_info.get('proxycommand'))

            if not (self.password or self.key_file):
                if host_info and host_info.get('identityfile'):
                    self.key_file = host_info.get('identityfile')[0]
Esempio n. 4
0
def get_host_details(host):
    cmd = "vagrant ssh-config {}".format(host)
    p = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
    config = paramiko.SSHConfig()
    config.parse(p.stdout)
    c = config.lookup(host)
    return {
        'ansible_host': c['hostname'],
        'ansible_port': c['port'],
        'ansible_user': c['user'],
        'ansible_private_key_file': c['identityfile'][0]
    }
Esempio n. 5
0
def get_ssh_configs(hosts):
    cmd = ['vagrant', 'ssh-config'] + hosts
    try:
        output = subprocess.check_output(cmd,
                                         universal_newlines=True,
                                         stderr=DEVNULL).decode()
    except subprocess.CalledProcessError:
        return None

    config = paramiko.SSHConfig()
    config.parse(StringIO(output))
    return config
Esempio n. 6
0
def get_host_details(host):
    cmd = f"vagrant ssh-config {host}"
    p = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
    ssh = paramiko.SSHConfig()
    ssh.parse(p.stdout)
    config = ssh.lookup(host)
    return {
        'ansible_host': config['hostname'],
        'ansible_port': config['port'],
        'ansible_user': config['user'],
        'ansible_private_key_file': config['identityfile'][0],
    }
Esempio n. 7
0
    def __init__(self):
        # self.jobInfos = []
        paramiko.util.log_to_file("ssh_log.log")  #<- sometimes throws problem
        self.client = paramiko.SSHClient()
        self.client._policy = paramiko.WarningPolicy()
        self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        self.ssh_config = paramiko.SSHConfig()
        user_config_file = os.path.expanduser("~/.ssh/config")
        if os.path.exists(user_config_file):
            with open(user_config_file) as f:
                self.ssh_config.parse(f)
Esempio n. 8
0
 def __init__(self, host, interval):
     self.client = paramiko.SSHClient()
     self.client._policy = paramiko.WarningPolicy()
     ssh_config = paramiko.SSHConfig()
     user_config_file = os.path.expanduser("~/.ssh/config")
     with open(user_config_file) as f:
         ssh_config.parse(f)
     user_config = ssh_config.lookup(host)
     keys = user_config['identityfile']
     key = paramiko.RSAKey.from_private_key_file(keys[0])
     self.client.connect(user_config['hostname'], self.port,
                         user_config['user'], None, key)
Esempio n. 9
0
 def __getDataHost(self, host, ssh_config_file=None):
     """
     This function returns a dictionary for the given host
     The structure of the dictionary is the following
     {'hostname': IP, 'user': usernameofthemachine}
     """
     # ssh config file
     if ssh_config_file is not None:
         config = paramiko.SSHConfig()
         #config.parse(open(CONS.SSHCONFIG))
         config.parse(open(ssh_config_file))
         return config.lookup(host)
Esempio n. 10
0
def sendDirsToIMR(dirs, vaspfiles):

    print("type your passwd for IMR supercomputer node")
    passwd = getpass()
    config_file = os.path.join(os.getenv('HOME'), '.ssh/config')
    ssh_config = paramiko.SSHConfig()
    ssh_config.parse(open(config_file, 'r'))
    # please adjust for your environment
    lkup = ssh_config.lookup('super.imr')

    # ProxyCommand setup
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.load_system_host_keys()
    print("what found in config file")
    print(lkup)

    ssh.connect(lkup['hostname'],
                username=lkup['user'],
                sock=paramiko.ProxyCommand(lkup['proxycommand']),
                password=passwd)

    sftp = ssh.open_sftp()

    #get pass for home
    stdin, stdout, stderr = ssh.exec_command('echo $HOME')
    outlines = stdout.readlines()
    result = outlines[0].rstrip('\n')
    print(result)
    #please change property to your enviroment
    workingdir = result + '/work/'
    for i in dirs:

        mkdircommand = 'mkdir ' + workingdir + i
        stdin, stdout, stderr = ssh.exec_command(mkdircommand)
        outlines = stdout.readlines()
        result = ''.join(outlines)
        print(result)

    for i in dirs:

        #TODO catch stderr
        for f in vaspfiles:
            origin = "./" + i + "/" + f
            print("origin:" + origin)
            #print(os.path.exists(origin))
            target = workingdir + i + "/" + f
            print("target:" + target)
            sftp.put(origin, target)

    sftp.close()
    ssh.close()
Esempio n. 11
0
    def make_ssh_connection(self):
        if self._ssh_client is not None:
            return True

        self._ssh_client = paramiko.SSHClient()
        self._ssh_client.load_system_host_keys()
        self._ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        # Merge any configuration present in ssh-config with the ones passed on the command-line
        ssh_config = paramiko.SSHConfig()
        user_config_file = os.path.expanduser("~/.ssh/config")
        if os.path.exists(user_config_file):
            f = open(user_config_file)
            ssh_config.parse(f)
            f.close()

        user_config = ssh_config.lookup(self._host_ip)

        # If SSH port is not passed by the user then lookup in ssh-config, if port is configured there then use it,
        # otherwise use the default ssh port '22'
        if self._ssh_port is None or self._ssh_port < 1:
            if 'port' in user_config:
                self._ssh_port = user_config['port']
            else:
                self._ssh_port = 22
        else:
            self._ssh_port = int(self._ssh_port)

        # If SSH username is not passed by the user then lookup in ssh-config, if username is configured there then
        # use it, otherwise use the current system user
        if self._ssh_user is None:
            if 'username' in user_config:
                self._ssh_user = user_config['username']
            else:
                self._ssh_user = pwd.getpwuid(os.getuid())[0]

        cfg = dict(hostname=self._host_ip, username=self._ssh_user, port=self._ssh_port)

        if 'identityfile' in user_config:
            cfg['key_filename'] = user_config['identityfile']

        try:
            print("Connecting to '%s'@'%s'" % (self._ssh_user, self._host))
            self._ssh_client.connect(**cfg)
        except paramiko.SSHException as e:
            print("Error connecting to '%s': %s" % (self._host, repr(e)))
            return False
        except socket.error as e:
            print("Failed to connect to '%s': %s" % (self._host, repr(e)))
            return False

        return True
Esempio n. 12
0
    def __identity_file(self, node_name, username, port):
        """ It processes the Identity File for use with remote node

        Returns:
            tuple(identity_file, host, username, port)
        """

        ssh_config = paramiko.SSHConfig()
        user_config_file = os.path.expanduser("~/.ssh/config")
        if os.path.exists(user_config_file):
            with open(user_config_file) as f:
                ssh_config.parse(f)
        user_config = ssh_config.lookup(node_name)

        identity_file = None
        if 'identityfile' in user_config:
            host = user_config['hostname']
            identity_file = user_config['identityfile']
            if not username:
                username = user_config['user']
            if not port:
                port = user_config['port']

        if identity_file is None:
            self.raise_error(
                'Clouder does not have a record in the ssh config to '
                'connect to your node.\n'
                'Make sure there is a "%s" record in the "~/.ssh/config" '
                'of the Clouder system user.\n'
                'To easily add this record, you can click on the '
                '"Reinstall" button of the node record, or the '
                '"Reset Key" button of the service record you are '
                'trying to access',
                self._name,
            )

        # Security with latest version of Paramiko
        # https://github.com/clouder-community/clouder/issues/11
        if isinstance(identity_file, list):
            identity_file = identity_file[0]

        # Probably not useful anymore, to remove later
        if not isinstance(identity_file, basestring):
            self.raise_error(
                'For an unknown reason, the variable identityfile '
                'in the connect ssh function is invalid. Please report '
                'this message.\n'
                'IdentityFile: "%s", Type: "%s"',
                (identity_file, type(identity_file)),
            )

        return identity_file, host, username, int(port)
Esempio n. 13
0
def cleanFilesOnECCHost(files, host):
    import paramiko
    logger = getLogger(__name__)
    filesUploaded = []
    if len(files) < 1:
        return filesUploaded

    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.load_system_host_keys()

    ssh_config = paramiko.SSHConfig()
    user_config_file = os.path.expanduser("~/.ssh/config")
    if os.path.exists(user_config_file):
        with open(user_config_file) as f:
            ssh_config.parse(f)
    host = socket.getfqdn(host)
    cfg = {'hostname': host, 'username': getpass.getuser()}
    user_config = ssh_config.lookup(cfg['hostname'])
    for k in ('hostname', 'username', 'port'):
        if k in user_config:
            cfg[k] = user_config[k]

    if 'identityfile' in user_config:
        cfg['key_filename'] = user_config['identityfile']
    if 'proxycommand' in user_config:
        cfg['sock'] = paramiko.ProxyCommand(user_config['proxycommand'])

    logger.info("Connecting to host %s", host)
    try:
        client.connect(**cfg)
    except EnvironmentError as e:
        logger.error("Could not connect to host %s. %d:%s", host, e.errno,
                     os.strerror(e.errno))
        return filesUploaded
    # Setup sftp connection and transmit this script
    sftp = client.open_sftp()

    for f in files:
        f = os.path.join(eccFileDir, os.path.basename(f))
        try:
            sftp.remove(f)
        except Exception:
            logger.exception("Could not delete '%s' on host %s.", f, host)
            continue
    try:
        dirFiles = sftp.listdir(eccFileDir)
        if dirFiles and len(dirFiles) == 0:
            sftp.rmdir(eccFileDir)
    except Exception:
        logger.exception("Could not delete directory '%s' on host %s.",
                         eccFileDir, host)
Esempio n. 14
0
    def _get_ssh_config(config_path='~/.ssh/config'):
        """Extract the configuration located at ``config_path``.

        Returns:
            paramiko.SSHConfig: the configuration instance.
        """
        ssh_config = paramiko.SSHConfig()
        try:
            with open(os.path.realpath(os.path.expanduser(config_path))) as f:
                ssh_config.parse(f)
        except IOError:
            pass
        return ssh_config
Esempio n. 15
0
def lookup_host_in_ssh_config(hostname):
    parser = paramiko.SSHConfig()
    parser.parse(open(settings.TASK_CONFIG_BACKUP_SSH_CONFIG))
    config = parser.lookup(hostname)
    if 'port' in config:
        ssh_port = int(config['port'])
    else:
        ssh_port = 22
    if 'hostname' in config:
        ssh_hostname = config['hostname']
    else:
        ssh_hostname = hostname
    return ssh_hostname, ssh_port
Esempio n. 16
0
def get_host_details(host):
    """vagrant.py --host <hostname> function"""
    cmd = ["vagrant", "ssh-config", host]
    ssh_config = subprocess.check_output(cmd).decode("utf-8")
    config = paramiko.SSHConfig()
    config.parse(io.StringIO(ssh_config))
    host_config = config.lookup(host)
    return {
        'ansible_host': host_config['hostname'],
        'ansible_port': host_config['port'],
        'ansible_user': host_config['user'],
        'ansible_private_key_file': host_config['identityfile'][0]
    }
Esempio n. 17
0
    def _load_user_ssh_config(hostname):
        import paramiko

        user_config_file = RemoteSSH.ssh_config_filename()
        user_ssh_config = {}
        if hostname and os.path.exists(user_config_file):
            ssh_config = paramiko.SSHConfig()
            with open(user_config_file) as f:
                # For whatever reason parsing directly from f is unreliable
                f_copy = io.StringIO(f.read())
                ssh_config.parse(f_copy)
            user_ssh_config = ssh_config.lookup(hostname)
        return user_ssh_config
Esempio n. 18
0
def get_info_from_ssh_config(hostname):
    user_config_file = os.path.expanduser("~/.ssh/config")
    ssh_config = paramiko.SSHConfig()
    if os.path.exists(user_config_file):
        with open(user_config_file) as f:
            ssh_config.parse(f)
    cfg = ssh_config.lookup(hostname)
    full_hostname = cfg["hostname"]
    username = cfg["user"]
    proxy = (
        paramiko.ProxyCommand(cfg["proxycommand"]) if "proxycommand" in cfg else None
    )
    return username, full_hostname, proxy
Esempio n. 19
0
def ssh_config_run(host, cmd):
    ssh = paramiko.SSHClient()
    ssh.load_system_host_keys()
    ssh._policy = paramiko.WarningPolicy()
    #ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    ssh_config = paramiko.SSHConfig()
    user_config_file = os.path.expanduser("~/.ssh/config")
    try:
        with open(user_config_file) as f:
            ssh_config.parse(f)
    except:
        print("{} file could not be found. Aborting.".format(user_config_file))
        sys.exit(1)
    user_config = ssh_config.lookup(host)
    cfg = {
        'hostname': user_config['hostname'],
        'username': user_config['user'],
        'look_for_keys': False
    }

    if 'proxycommand' in user_config:
        cfg['sock'] = paramiko.ProxyCommand(user_config['proxycommand'])

    ssh.connect(**cfg)
    retout = []
    for m in cmd:
        print(host, m)
        if m[:4] == 'sudo':
            transport = ssh.get_transport()
            session = transport.open_session()
            session.set_combine_stderr(True)
            session.get_pty()
            session.exec_command(m)
            stdin = session.makefile('wb', -1)
            stdout = session.makefile('rb', -1)
            stdin.write('Ranchyang!1\n')
            stdin.flush()
            for line in stdout.read().splitlines():
                print 'host: %s: %s' % (host, line)
            continue
        stdin, stdout, stderr = ssh.exec_command(m)
        outt = stdout.readlines()
        retout.append(outt)
        for o in outt:
            print(host, 'out', o)
        err = stderr.readlines()
        for e in err:
            print(host, 'err', e)
    ssh.close()
    return retout
Esempio n. 20
0
    def _sshconf_lkup(self):
        home = os.getenv('HOME')
        if not home:
            return
        sshconf_path = os.path.join(os.getenv('HOME'), '.ssh/config')
        if not os.path.exists(sshconf_path):
            return

        sshconf = paramiko.SSHConfig()
        sshconf.parse(open(sshconf_path, 'r'))
        found = sshconf.lookup(self._hostname)
        self._hostname = found.get('hostname', self._hostname)
        self._port = found.get('port', self._port)
        self._auth_user = found.get('user')
Esempio n. 21
0
 def __init__(self):
     super(_SSHClientBuilder, self).__init__()
     self._hostname = None
     self._port = 22
     self._username = None
     self._password = None
     self._config = paramiko.SSHConfig()
     self._client_class = paramiko.SSHClient
     self._missing_host_key_policy = paramiko.AutoAddPolicy
     self._timeout = DEFAULT_TIMEOUT
     self._banner_timeout = DEFAULT_TIMEOUT
     self._allow_agent = None
     self._proxy_command = None
     self._sock = None
Esempio n. 22
0
    def connect(self):
        """Connect to the SLURM master node."""
        config = paramiko.SSHConfig()
        config.parse(open(self.sshconfigfile))
        host = config.lookup("cluster")
        self.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        proxy = paramiko.ProxyCommand(host['proxycommand'])
        super(SlurmSSHClient, self).connect(host['hostname'],
                                            22,
                                            username=self.usr,
                                            key_filename=host["identityfile"],
                                            sock=proxy)

        return self
Esempio n. 23
0
    def put(self):
        """sync data"""
        logging.basicConfig(level=logging.DEBUG)
        hostname = self.hostname
        print(hostname)
        username = self.username

        mypath = '/data/kafka-to-nexus/nicos000187.hdf'
        mypath = os.getcwd() + '/x.txt'
        print(mypath)
        basepath = '/users/detector/experiments/V20/'

        prop = GetProposal()
        file_mgr = GetFiles()
        file_mgr.set_base('./demo')
        file_array = file_mgr.get()

        remote_directory = basepath + prop.fetch()
        remote_directory = '/users/' + username + '/'
        print("remote_dir", remote_directory)

        from os.path import expanduser
        home = expanduser("~")
        ssh_config_file = os.path.expanduser("~/.ssh/config")
        proxy = None
        if os.path.exists(ssh_config_file):
            conf = paramiko.SSHConfig()
            with open(ssh_config_file) as ssh_conf:
                conf.parse(ssh_conf)
            host_config = conf.lookup('login')
            if 'proxycommand' in host_config:
                print(host_config['proxycommand'])
                proxy = paramiko.ProxyCommand(host_config['proxycommand'])
        keyname = home + "/.ssh/id_ed25519"
        print(username)
        print(keyname)
        ed25519_key = paramiko.Ed25519Key.from_private_key_file(keyname)

        ssh = paramiko.SSHClient()
        ssh.load_system_host_keys()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(hostname, username=username, pkey=ed25519_key, sock=proxy)
        scp = SCPClient(ssh.get_transport())
        for file in file_array:
            mypath = file
            basename = os.path.basename(mypath)
            remotepath = remote_directory + '/' + basename
            print(remotepath)
            scp.put(mypath, recursive=True, remote_path=remotepath)
        scp.close()
Esempio n. 24
0
def get_host_details(host):
    if debugging:
        print(host)
    cmd = "vagrant ssh-config {}".format(host)
    p = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
    config = paramiko.SSHConfig()
    config.parse(p.stdout)
    c = config.lookup(host)
    return {
        "ansible_host": c["hostname"],
        "ansible_port": c["port"],
        "ansible_user": c["user"],
        "ansible_private_key_file": c["identityfile"][0]
    }
Esempio n. 25
0
def _ssh_client(host_name, host_args, **kwargs):
    """prepare a paramiko.SSHClient with host keys and our
    custom config. Returns client object and connection arguments.
    Example usage:
```
    client, args = _ssh_client('myhost.domain.name', {})
    client.connect(**args)
    client.exec_command('echo hello')
```
    """

    client = paramiko.SSHClient()

    client.load_system_host_keys()
    if not config.ssh_strict_host_key_checking:
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    args = {
        'hostname':
        host_name,
        'username':
        host_args.get('ssh-user', config.ssh_user),
        'key_filename':
        host_args.get('ssh-id-rsa-file', config.ssh_id_rsa_file),
        'password':
        host_args.get('ssh-id-rsa-password', config.ssh_id_rsa_password),
        'timeout':
        host_args.get('ssh-timeout', 5)
    }

    try:
        proxy_command = host_args.get('ssh-proxycommand')
        if proxy_command is None:
            with open(config.ssh_config_file, 'r') as fin:
                conf = paramiko.SSHConfig()
                conf.parse(fin)

                proxy_command = conf.lookup(host_name).get('proxycommand')

        if proxy_command is not None:
            logging.debug('[{}] Using proxy command {}'.format(
                host_name, proxy_command))
            args.update({'sock': paramiko.ProxyCommand(proxy_command)})

    except Exception:
        pass

    args.update(**kwargs)

    return client, args
Esempio n. 26
0
 def sshConfig(self, name):
     p = Popen(['vagrant', 'ssh-config', name],
               stdout=PIPE,
               stderr=None,
               stdin=None,
               cwd='tests/',
               )
     p.wait()
     if p.returncode != 0:
         raise RuntimeError('Could not get ssh-config for ' + repr(name))
     ssh_config = paramiko.SSHConfig()
     ssh_config.parse(p.stdout)
     p.stdout.close()
     return ssh_config.lookup(name)
Esempio n. 27
0
 def _read_login_ssh_config(host, username, port_number, proxy_cmd):
     ssh_config_file = os.path.expanduser("~/.ssh/config")
     if os.path.exists(ssh_config_file):
         conf = paramiko.SSHConfig()
         with open(ssh_config_file) as f:
             conf.parse(f)
         port = int(
             PythonSSHClient._get_ssh_config_port(conf, host, port_number))
         user = PythonSSHClient._get_ssh_config_user(conf, host, username)
         proxy_command = PythonSSHClient._get_ssh_config_proxy_cmd(
             conf, host, proxy_cmd)
         host = PythonSSHClient._get_ssh_config_host(conf, host)
         return host, user, port, proxy_command
     return host, username, port_number, proxy_cmd
Esempio n. 28
0
  def __init__(self,
               name,
               ip_addr,
               base_dir,
               shell_setup_commands=[],
               use_ssh=True,
               ssh_key_file=None,
               ssh_port=22,
               ssh_username=None,
               ssh_config_file_path=None,
               spy_port=None,
               **kwargs):

    raise Exception(f'Deprecated!!')
    del kwargs
    self.name = name
    self._ip_addr = ip_addr
    self.ssh_key_file = ssh_key_file
    self.ssh_port = ssh_port
    self._ssh_client = None
    self._sftp_client = None
    self.ssh_username = ssh_username
    self._base_dir = base_dir
    self.spy_port = spy_port
    assert isinstance(shell_setup_commands, list)
    self.shell_setup_commands = ["cd '%s'" % base_dir
                                 ] + list(shell_setup_commands)
    self.use_ssh = use_ssh
    self.reserved_ports = []
    # If key file is not given, check
    # if default config option is viable
    if use_ssh and self.ssh_key_file is None:
      if ssh_config_file_path is None and ssh_username is not None:
        ssh_config_file_path = '/home/%s/.ssh/config' % ssh_username
      config = paramiko.SSHConfig()
      with open(ssh_config_file_path, 'r') as f:
        config.parse(f)

      res = config.lookup(ip_addr)
      if 'identityfile' in res:
        self.ssh_key_file = res['identityfile']
      else:
        raise Exception(
            'ssh key file not provided and default not found in ssh config file at %s'
            % ssh_config_file_path)

    self._capacity = None
    self._util = None
    self.collected_spy_stats = False
Esempio n. 29
0
def parse_ssh_config(
    ssh_config: str | paramiko.SSHConfig | SSHConfigsDictT | None,
    host: str,
) -> HostsSSHConfigs:
    """Parse ssh config to get real connection parameters.

    :param ssh_config: SSH configuration for connection. Maybe config path, parsed as dict and paramiko parsed.
    :type ssh_config:
        typing.Union[
            str,
            paramiko.SSHConfig,
            typing.Dict[str, typing.Dict[str, typing.Union[str, int, bool, typing.List[str]]]],
            None
        ]
    :param host: remote hostname
    :type host: str
    :return: parsed ssh config if available
    :rtype: HostsSSHConfigs
    """
    if isinstance(ssh_config, paramiko.SSHConfig):
        return _parse_paramiko_ssh_config(ssh_config, host)

    if isinstance(ssh_config, dict):
        return _parse_dict_ssh_config(ssh_config, host)

    if isinstance(ssh_config, str):
        ssh_config_path = pathlib.Path(ssh_config).expanduser()
        if ssh_config_path.exists():
            real_config = paramiko.SSHConfig()
            with ssh_config_path.open("t", encoding="utf-8") as f_config:
                real_config.parse(f_config)
            return _parse_paramiko_ssh_config(real_config, host)

    system_ssh_config: paramiko.config.SSHConfig | None = _parse_ssh_config_file(
        SSH_CONFIG_FILE_SYSTEM)
    user_ssh_config: paramiko.config.SSHConfig | None = _parse_ssh_config_file(
        SSH_CONFIG_FILE_USER)

    if system_ssh_config is not None:
        config = _parse_paramiko_ssh_config(system_ssh_config, host)
    else:
        config = HostsSSHConfigs({host: SSHConfig(host)})

    if user_ssh_config is not None:
        user_config = _parse_paramiko_ssh_config(user_ssh_config, host)
        for hostname, cfg in user_config.items():
            config[hostname] = config[hostname].overridden_by(cfg)

    return config
Esempio n. 30
0
    def open(
        self,
        hostname: Optional[str],
        username: Optional[str],
        password: Optional[str],
        port: Optional[int],
        platform: Optional[str],
        extras: Optional[Dict[str, Any]] = None,
        configuration: Optional[Config] = None,
    ) -> None:
        extras = extras or {}

        client = paramiko.SSHClient()
        client._policy = paramiko.WarningPolicy()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        ssh_config = paramiko.SSHConfig()
        ssh_config_file = configuration.ssh.config_file  # type: ignore
        if os.path.exists(ssh_config_file):
            with open(ssh_config_file) as f:
                ssh_config.parse(f)
        parameters = {
            "hostname": hostname,
            "username": username,
            "password": password,
            "port": port,
        }

        user_config = ssh_config.lookup(hostname)
        for k in ("hostname", "username", "port"):
            if k in user_config:
                parameters[k] = user_config[k]

        if "proxycommand" in user_config:
            parameters["sock"] = paramiko.ProxyCommand(
                user_config["proxycommand"])

        self.state["ssh_forward_agent"] = user_config.get(
            "forwardagent") == "yes"

        # TODO configurable
        #  if ssh_key_file:
        #      parameters['key_filename'] = ssh_key_file
        if "identityfile" in user_config:
            parameters["key_filename"] = user_config["identityfile"]

        extras.update(parameters)
        client.connect(**extras)
        self.connection = client