Exemple #1
0
Fichier : ssh.py Projet : timff/st2
    def __init__(self,
                 host,
                 user=None,
                 password=None,
                 port=None,
                 key=None,
                 connect_max_retries=2):
        ssh_config = paramiko.SSHConfig()
        _ssh_config_file = os.path.sep.join(
            [os.path.expanduser('~'), '.ssh', 'config'])

        if os.path.exists(_ssh_config_file):
            ssh_config.parse(open(_ssh_config_file))
        host_config = ssh_config.lookup(host)
        resolved_address = (host_config['hostname']
                            if 'hostname' in host_config else host)
        _user = host_config['user'] if 'user' in host_config else None
        if user:
            user = user
        else:
            user = _user
        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(paramiko.MissingHostKeyPolicy())
        self.client = client
        self.channel = None
        self.user = user
        self.password = password
        self.key = key
        self.port = port if port else 22
        self.host = resolved_address
        self._max_retries = 2
        self._connect_to_host()
        self.running = False
Exemple #2
0
    def _create_channel(self, timeout=10.0):
        """
        Create a secure tunnel across an SSH Transport.
        """
        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(paramiko.MissingHostKeyPolicy())

        try:
            connection = client.connect(self._ssh_to, username=self._login, \
                password=self._passwd, banner_timeout=2.0)
        except Exception as e:
            cprint.colorPrint(
                'Could not do SSH connect to %s. Error: %s' %
                (self._ssh_to, e), 'r')
#raise Exception("ERROR")

        try:
            self._channel = client.invoke_shell()
            self._channel.settimeout(timeout)
            # To avoid gc of SSHClient object associated with the channel
            self._channel.keep_this = client
        except SSHException as e:
            cprint.colorPrint(
                'Could not open SSH channel on %s. Error: %s' %
                (self._ssh_to, e), 'r')
#raise Exception("ERROR")
        self._channel_fd = self._channel.fileno()
def ssh_client(ip, user, private_key_filepath=None, password=None,
               proxy_settings=None):
    """
    Retrieves and attemts an SSH connection
    :param ip: the IP of the host to connect
    :param user: the user with which to connect
    :param private_key_filepath: when None, password is required
    :param password: when None, private_key_filepath is required
    :param proxy_settings: instance of os_credentials.ProxySettings class
                           (optional)
    :return: the SSH client if can connect else false
    """
    logger.debug('Retrieving SSH client')
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.MissingHostKeyPolicy())

    try:
        proxy_cmd = None
        if proxy_settings and proxy_settings.ssh_proxy_cmd:
            proxy_cmd_str = str(proxy_settings.ssh_proxy_cmd.replace('%h', ip))
            proxy_cmd_str = proxy_cmd_str.replace("%p", '22')
            proxy_cmd = paramiko.ProxyCommand(proxy_cmd_str)

        pk_abs_path = None
        if not password and private_key_filepath:
            pk_abs_path = os.path.expanduser(private_key_filepath)

        ssh.connect(
            ip, username=user, key_filename=pk_abs_path, password=password,
            sock=proxy_cmd)
        logger.info('Obtained SSH connection to %s', ip)
        return ssh
    except Exception as e:
        logger.debug('Unable to connect via SSH with message - ' + str(e))
Exemple #4
0
    def _connect_tunnel(self, host, **paramiko_kwargs):
        """Connects to SSH server via an intermediate SSH tunnel server.
        client (me) -> tunnel (ssh server to proxy through) ->
        ``self.host`` (ssh server to run command)

        :rtype: :py:class:`paramiko.SSHClient` Client to remote SSH destination
        via intermediate SSH tunnel server.
        """
        self.proxy_client = paramiko.SSHClient()
        self.proxy_client.set_missing_host_key_policy(
            paramiko.MissingHostKeyPolicy())
        self._connect(self.proxy_client, self.proxy_host, self.proxy_port,
                      user=self.proxy_user, password=self.proxy_password,
                      pkey=self.proxy_pkey, **paramiko_kwargs)
        logger.info("Connecting via SSH proxy %s:%s -> %s:%s", self.proxy_host,
                    self.proxy_port, host, self.port,)
        try:
            proxy_channel = self.proxy_client.get_transport().open_channel(
                'direct-tcpip', (host, self.port,), ('127.0.0.1', 0),
                timeout=self.timeout)
            sleep(0)
            return self._connect(self.client, host, self.port,
                                 sock=proxy_channel,
                                 **paramiko_kwargs)
        except (ChannelException, paramiko.SSHException) as ex:
            error_type = ex.args[1] if len(ex.args) > 1 else ex.args[0]
            raise ConnectionErrorException(
                "Error connecting to host '%s:%s' - %s",
                host, self.port, str(error_type))
Exemple #5
0
def upload_binary_to_client(hostname, port, username, password, file_src_path,
                            binary_path, id_file):
    try:
        t = paramiko.Transport((hostname, port))
        pkey = None
        if id_file:
            pkey = paramiko.RSAKey.from_private_key_file(id_file)
            t.connect(username=username, pkey=pkey)
        else:
            t.connect(username=username, password=password)
        sftp = paramiko.SFTPClient.from_transport(t)

        # upload binary
        sftp.put(file_src_path, binary_path)
        t.close()

        client = paramiko.SSHClient()
        client.load_system_host_keys()
        client.set_missing_host_key_policy(paramiko.MissingHostKeyPolicy())
        client.connect(hostname, port, username, password, pkey)

    except paramiko.AuthenticationException as e:
        raise Exception("Authentification error: " + e[0])
    except Exception, e:
        try:
            t.close()
            client.close()
        except:
            pass
        raise Exception("Caught exception when uploading binary [" +
                        binary_path + "]: " + str(e))
Exemple #6
0
    def __init__(
        self,
        config: Config,
        hostname: str,
        username: str,
        key: str = None,
    ):
        super().__init__(config=config)
        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)

        # Thanks https://gist.github.com/acdha/6064215
        user_config = ssh_config.lookup(hostname)
        if 'hostname' in user_config:
            hostname = user_config['hostname']
        if 'user' in user_config:
            username = user_config['user']
        if 'identityfile' in user_config:
            key = user_config['identityfile'][0]

        self.client = paramiko.SSHClient()
        self.client.set_missing_host_key_policy(
            paramiko.MissingHostKeyPolicy())
        self.client.connect(
            hostname=hostname,
            username=username,
            pkey=paramiko.RSAKey.from_private_key_file(
                key or os.path.expanduser("~/.ssh/id_rsa")),
        )
        self.env: Dict[str, str] = {}
def attempt(Password):

    IP = "127.0.0.1"
    USER = "******"
    PORT = 22

    try:

        ssh = paramiko.SSHClient()
        ssh.load_system_host_keys()
        ssh.set_missing_host_key_policy(paramiko.MissingHostKeyPolicy())

        try:
            ssh.connect(IP, port=PORT, username=USER, password=Password)
            print("Connected successfully. Password = "******"Incorrect password: "******"Most probably this is caused by a missing host key")
            pass
        except Exception as error:
            print("Unknown error: " + error)
            pass
        ssh.close()

    except Exception as error:
        print(error)
Exemple #8
0
 def bruteforce(self):
     with open(self.passwordfile, 'r') as f:
         passwords = f.read()
     pwds = passwords.splitlines()
     for pwd in pwds:
         try:
             ssh_client = paramiko.SSHClient()
             ssh_client.load_system_host_keys()
             ssh_client.set_missing_host_key_policy(
                 paramiko.MissingHostKeyPolicy())
             try:
                 ssh_client.connect(self.IP,
                                    port=self.port,
                                    username=self.username,
                                    password=pwd)
                 print("Password found: " + pwd)
                 return pwd
                 break
             except paramiko.AuthenticationException as error:
                 print("Failed Attempt: " + pwd)
                 continue
             except socket.error as error:
                 print("Socket error: ", error)
                 continue
             except paramiko.SSHException as error:
                 print("SSHException: ", error)
                 continue
             except Exception as error:
                 print("Exception: ", error)
                 continue
             ssh_client.close()
         except Exception as error:
             print("OUTSIDE: ", error)
             return False
     return False
Exemple #9
0
 def run_cmd(self, host, key_file, cmd, expect_status=0):
     """
     run cmd on host via ssh using keyfile.
     if the result of the command is different
     than expect_status, raise an exception.
 """
     print "Running \"{0}\" on {1}".format(cmd, host)
     cmd = cmd.replace('"', '\"')
     ssh = paramiko.SSHClient()
     ssh.set_missing_host_key_policy(
         paramiko.MissingHostKeyPolicy())  # ignore unknown hosts
     ssh.connect(host,
                 username='******',
                 key_filename=key_file,
                 password='')
     chan = ssh.get_transport().open_session()
     chan.exec_command(cmd)
     stdin = chan.makefile('wb')
     stdout = chan.makefile('rb')
     stderr = chan.makefile_stderr('rb')
     status = chan.recv_exit_status()
     if status != expect_status:
         raise Exception(
             "command failed ({0}) on host {1}: {2}\n{3}".format(
                 status, host, cmd,
                 ''.join(stdout.readlines() + stderr.readlines())))
     ssh.close()
Exemple #10
0
 def connect(self):
     try:
         self._client.set_missing_host_key_policy(
             paramiko.MissingHostKeyPolicy())
         self._client.connect(hostname=self._address,
                              port=self._port,
                              username=self._login,
                              password=self._password,
                              timeout=self._timeout)
         channel = self._client.invoke_shell()
         channel.set_combine_stderr(False)
         channel.settimeout(2)
         self._shell = self.StandartChannels(
             stdin=channel.makefile('wb'),
             stdout=channel.makefile('r'),
             stderr=channel.makefile_stderr('r'))
         self.interactive_command('echo test')
     except paramiko.AuthenticationException:
         self.logger.debug(f'AuthenticationError {self._login}'
                           f' on {self._address}')
         raise AuthenticationFailure(login=self._login,
                                     password=self._password,
                                     address=self._address,
                                     port=self._port)
     except socket.timeout:
         self.logger.debug(f'Host {self._address} is not available')
         raise HostNotResponsible(address=self._address, port=self._port)
     except paramiko.SSHException:
         self.logger.debug(f'TransportError')
         raise TransportException(address=self._address, port=self._port)
Exemple #11
0
 def _connect_tunnel(self):
     """Connects to SSH server via an intermediate SSH tunnel server.
     client (me) -> tunnel (ssh server to proxy through) -> \
     destination (ssh server to run command)
     
     :rtype: `:mod:paramiko.SSHClient` Client to remote SSH destination
     via intermediate SSH tunnel server.
     """
     self.proxy_client = paramiko.SSHClient()
     self.proxy_client.set_missing_host_key_policy(
         paramiko.MissingHostKeyPolicy())
     self._connect(self.proxy_client, self.proxy_host, self.proxy_port)
     logger.info(
         "Connecting via SSH proxy %s:%s -> %s:%s",
         self.proxy_host,
         self.proxy_port,
         self.host,
         self.port,
     )
     try:
         proxy_channel = self.proxy_client.get_transport().\
           open_channel('direct-tcpip', (self.host, self.port,),
                       ('127.0.0.1', 0))
         return self._connect(self.client,
                              self.host,
                              self.port,
                              sock=proxy_channel)
     except channel_exception, ex:
         error_type = ex.args[1] if len(ex.args) > 1 else ex.args[0]
         raise ConnectionErrorException(
             "Error connecting to host '%s:%s' - %s", self.host, self.port,
             str(error_type))
def handler(context, inputs):
  
  
  salt_master = inputs["customProperties"] ["salt_master"]  # ip du salt master
  username="******"
  salt_master_password = inputs["customProperties"] ["salt_master_password"]  # password de username sur le master
 
 # Creation de la commande
  minion_ID = inputs["resourceNames"][0] +"*"         # on rajoute l'etoile pour prendre en compte le hostname ou le FQDN
  cmd_to_execute="salt-key -y --delete=" +minion_ID

  #logs
  print("server salt master : " +salt_master)
  print("minion ID : " +minion_ID)
  print("command to execute : " +cmd_to_execute)

  # execution SSH
  client = paramiko.SSHClient()
  client.set_missing_host_key_policy(paramiko.MissingHostKeyPolicy())    # pas de check de clé
  client.connect(salt_master, username=username, password=salt_master_password)
  ssh_stdin, ssh_stdout, ssh_stderr = client.exec_command(cmd_to_execute)
  
  # affichage de la sortie de la commande
  for line in ssh_stdout:
    print('... ' + line.strip('\n'))
  
  client.close()

  outputs={"status":"Unregister minion terminé"}
  return outputs
  
Exemple #13
0
def ssh_client(ip, user, private_key_filepath, proxy_settings=None):
    """
    Retrieves and attemts an SSH connection
    :param ip: the IP of the host to connect
    :param user: the user with which to connect
    :param private_key_filepath: the path to the private key file
    :param proxy_settings: optional proxy settings in the form <hostname|IP>:<port>
    :return: the SSH client if can connect else false
    """
    import paramiko

    logger.debug('Retrieving SSH client')
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.MissingHostKeyPolicy())
    proxy = None
    if proxy_settings:
        logger.debug('Setting up SSH proxy settings')
        tokens = re.split(':', proxy_settings)
        proxy = paramiko.ProxyCommand('../ansible/conf/ssh/corkscrew ' +
                                      tokens[0] + ' ' + tokens[1] + ' ' + ip +
                                      ' 22')
        logger.info('Attempting to connect to ' + ip)

    try:
        ssh.connect(ip,
                    username=user,
                    key_filename=private_key_filepath,
                    sock=proxy)
        return ssh
    except Exception as e:
        logger.warn('Unable to connect via SSH with message - ' + e.message)
Exemple #14
0
 def set_sshcfg(self, **kw):
     node = kw['node']
     nodeinfo = kw['nodeinfo']
     tmp_remote_dir = "/tmp/%s/.ssh/" % nodeinfo['username']
     try:
         ssh_client = paramiko.SSHClient()
         ssh_client.set_missing_host_key_policy(
             paramiko.MissingHostKeyPolicy())
         ssh_client.connect(nodeinfo['bmcip'],
                            username=nodeinfo['username'],
                            password=nodeinfo['password'])
     except (NoValidConnectionsError) as e:
         return self.callback.error(
             "Unable to connect to bmc %s" % nodeinfo['bmcip'], node)
     if not ssh_client.get_transport().is_active():
         return self.callback.error(
             "SSH session to bmc %s is not active" % nodeinfo['bmcip'],
             node)
     if not ssh_client.get_transport().is_authenticated():
         return self.callback.error(
             "SSH session to bmc %s is not authenticated" %
             nodeinfo['bmcip'], node)
     ssh_client.exec_command("/bin/mkdir -p %s\n" % tmp_remote_dir)
     scp = SCPClient(ssh_client.get_transport())
     scp.put(self.copy_sh_file, tmp_remote_dir + "copy.sh")
     scp.put(self.local_public_key, tmp_remote_dir + "id_rsa.pub")
     ssh_client.exec_command("%s/copy.sh %s" %
                             (tmp_remote_dir, nodeinfo['username']))
     ssh_client.close()
     return self.callback.info("ssh keys copied to %s" % nodeinfo['bmcip'])
Exemple #15
0
    def _mock_ssh_sftp(self):
        # SSH
        self.m.StubOutWithMock(paramiko, "SSHClient")
        self.m.StubOutWithMock(paramiko, "MissingHostKeyPolicy")
        ssh = self.m.CreateMockAnything()
        paramiko.SSHClient().AndReturn(ssh)
        paramiko.MissingHostKeyPolicy()
        ssh.set_missing_host_key_policy(None)
        ssh.connect(mox.IgnoreArg(),
                    key_filename=mox.IgnoreArg(),
                    username='******')
        stdin = self.m.CreateMockAnything()
        stdout = self.m.CreateMockAnything()
        stderr = self.m.CreateMockAnything()
        stdout.read().AndReturn("stdout")
        stderr.read().AndReturn("stderr")
        ssh.exec_command(mox.IgnoreArg()).AndReturn((stdin, stdout, stderr))

        # SFTP
        self.m.StubOutWithMock(paramiko, "Transport")
        transport = self.m.CreateMockAnything()
        paramiko.Transport((mox.IgnoreArg(), 22)).AndReturn(transport)
        transport.connect(hostkey=None, username="******", pkey=mox.IgnoreArg())
        sftp = self.m.CreateMockAnything()
        self.m.StubOutWithMock(paramiko, "SFTPClient")
        paramiko.SFTPClient.from_transport(transport).AndReturn(sftp)
        sftp_file = self.m.CreateMockAnything()
        sftp.open(mox.IgnoreArg(), 'w').AndReturn(sftp_file)
        sftp_file.write(mox.IgnoreArg())
        sftp_file.close()
        sftp_file = self.m.CreateMockAnything()
        sftp.open(mox.IgnoreArg(), 'w').AndReturn(sftp_file)
        sftp_file.write(mox.IgnoreArg())
        sftp_file.close()
Exemple #16
0
def upload(host, username, password):
    import paramiko
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.MissingHostKeyPolicy())
    logging.info('connect %s', host)
    client.connect(host, 22, username, password)
    client.exec_command('mkdir -p /opt/goagent/{vps,log}')
    logging.info('open sftp...')
    sftp = client.open_sftp()
    logging.info('open sftp ok')
    sftp.chdir('/opt/goagent/vps')
    uploadlist = ['../local/proxylib.py', 'vps/*']
    for filename in sum((glob.glob(x) for x in uploadlist), []):
        logging.info('upload %s', filename)
        sftp.put(filename, '/opt/goagent/vps/%s' % os.path.basename(filename))
    cmds = [
        '/bin/cp -f /opt/goagent/vps/sysctl.conf /etc/',
        '/bin/cp -f /opt/goagent/vps/limits.conf /etc/security/',
        '/bin/ln -sf /opt/goagent/vps/goagentvps.sh /etc/init.d/goagentvps',
        'chmod +x /opt/goagent/vps/goagentvps.sh',
        'which update-rc.d && update-rc.d goagentvps defaults'
        'which chkconfig && chkconfig goagentvps on'
        'sysctl -p'
    ]
    client.exec_command(' ; '.join(cmds))
    client.exec_command('/etc/init.d/goagentvps stop')
    client.exec_command('/etc/init.d/goagentvps start')
Exemple #17
0
    def execute_command(self,
                        cmd,
                        ip="",
                        port=22,
                        timeout=7200,
                        environment={}):
        """Execute a command on a remote machine using ssh.

        :param cmd: command to be executed on a remote machine.
        :type cmd: str
        :param ip: machine's ip.
        :type ip: str
        :param port: machine's ssh port.
        :type port: int
        :param timout: stop execution after a certain time.
        :type timeout: int
        :return: subprocess object containing (returncode, stdout, stderr)
        """
        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(paramiko.MissingHostKeyPolicy())
        client.connect(hostname=ip, port=port, timeout=30)
        _, stdout, stderr = client.exec_command(cmd,
                                                timeout=timeout,
                                                environment=environment)
        try:
            out = stdout.read().decode()
            err = stderr.read().decode()
            rc = stdout.channel.recv_exit_status()
        except:
            stdout.channel.close()
            err = "Error Timeout Exceeded {}".format(timeout)
            out = ""
            rc = 124
        return Complete_Executuion(rc, out, err)
Exemple #18
0
 def __init__(self,
              host,
              port,
              username,
              password,
              look_for_keys=True):  # noqa too-many-arguments
     """
     Try to connect by SSH to remote server and set attribute client and ftp_client if connected.
     If not, set attribute init_error to error raised by connection.
     :param host: host of the server
     :param port: port of the server
     :param username: username from server
     :param password: password for user from server
     :param look_for_keys: False if password not required
     """
     super().__init__(host, port, username, password)
     self.look_for_keys = look_for_keys
     self.client = paramiko.SSHClient()
     self.client.set_missing_host_key_policy(
         paramiko.MissingHostKeyPolicy())
     self.init_error = None
     self.ftp_client = None
     try:
         self.client.connect(
             hostname=self.host,
             port=self.port,
             username=self.username,
             password=self.password,
             look_for_keys=self.look_for_keys,
         )
         self.ftp_client = self.client.open_sftp()
     except (paramiko.SSHException, gaierror) as error:
         self.init_error = error
         self.logger.error(error)
Exemple #19
0
    def __init__(self,
                 host,
                 username=None,
                 password=None,
                 pkey=None,
                 port=22,
                 timeout=15,
                 connect=True):
        self.host = host
        self.username = username
        self.password = password

        if pkey:
            if isinstance(pkey, paramiko.rsakey.RSAKey):
                self.pkey = pkey
            elif isinstance(pkey, str) and os.path.isfile(
                    os.path.expanduser(pkey)):
                pkey = os.path.expanduser(pkey)
                self.pkey = paramiko.RSAKey.from_private_key_file(pkey)
            else:
                raise DaskEc2Exception(
                    "pkey argument should be filepath or paramiko.rsakey.RSAKey"
                )
        else:
            self.pkey = None
        self.port = port
        self.timeout = timeout

        self.client = paramiko.SSHClient()
        self.client.set_missing_host_key_policy(
            paramiko.MissingHostKeyPolicy())
        self._sftp = None

        if connect:
            self.connect()
Exemple #20
0
 def _run_ssh_command(self, command):
     """Run a shell command on the Cloud Server via SSH."""
     with tempfile.NamedTemporaryFile() as private_key_file:
         private_key_file.write(self.private_key)
         private_key_file.seek(0)
         ssh = paramiko.SSHClient()
         ssh.set_missing_host_key_policy(paramiko.MissingHostKeyPolicy())
         ssh.connect(self.server.accessIPv4,
                     username="******",
                     key_filename=private_key_file.name)
         chan = ssh.get_transport().open_session()
         chan.settimeout(self.stack.timeout_mins * 60.0)
         chan.exec_command(command)
         try:
             # The channel timeout only works for read/write operations
             chan.recv(1024)
         except socket.timeout:
             raise exception.Error(
                 _("SSH command timed out after %s "
                   "minutes") % self.stack.timeout_mins)
         else:
             return chan.recv_exit_status()
         finally:
             ssh.close()
             chan.close()
Exemple #21
0
    def _mock_ssh_sftp(self, exit_code=0):
        # SSH
        self.m.StubOutWithMock(paramiko, "SSHClient")
        self.m.StubOutWithMock(paramiko, "MissingHostKeyPolicy")
        ssh = self.m.CreateMockAnything()
        paramiko.SSHClient().AndReturn(ssh)
        paramiko.MissingHostKeyPolicy()
        ssh.set_missing_host_key_policy(None)
        ssh.connect(mox.IgnoreArg(),
                    key_filename=mox.IgnoreArg(),
                    username='******')
        fake_chan = self.m.CreateMockAnything()
        self.m.StubOutWithMock(paramiko.SSHClient, "get_transport")
        chan = ssh.get_transport().AndReturn(fake_chan)
        fake_chan_session = self.m.CreateMockAnything()
        chan_session = chan.open_session().AndReturn(fake_chan_session)
        chan_session.exec_command(mox.IgnoreArg())
        chan_session.recv_exit_status().AndReturn(exit_code)

        # SFTP
        self.m.StubOutWithMock(paramiko, "Transport")
        transport = self.m.CreateMockAnything()
        paramiko.Transport((mox.IgnoreArg(), 22)).AndReturn(transport)
        transport.connect(hostkey=None, username="******", pkey=mox.IgnoreArg())
        sftp = self.m.CreateMockAnything()
        self.m.StubOutWithMock(paramiko, "SFTPClient")
        paramiko.SFTPClient.from_transport(transport).AndReturn(sftp)
        sftp_file = self.m.CreateMockAnything()
        sftp.open(mox.IgnoreArg(), 'w').AndReturn(sftp_file)
        sftp_file.write(mox.IgnoreArg())
        sftp_file.close()
        sftp_file = self.m.CreateMockAnything()
        sftp.open(mox.IgnoreArg(), 'w').AndReturn(sftp_file)
        sftp_file.write(mox.IgnoreArg())
        sftp_file.close()
Exemple #22
0
def ssh(hostname=None, command=None, username=None, password=None,):
    assert hostname and command and username and password, "ArrayCM.ssh requires valid args"

    _ssh = paramiko.SSHClient()
    _ssh.set_missing_host_key_policy(paramiko.MissingHostKeyPolicy())

    if hostname:  # TODO check hostname validation
        try:
            log.debug('_cli_ SSHClient: {!r} SSH_stdin: {!r}'.format(hostname, command))
            _ssh.connect(hostname=hostname, username=username, password=password)
        except(TimeoutError, paramiko.ssh_exception.AuthenticationException, socket.error) as e:
            raise GenericError(hostname, command, e)
        else:
            std_in, std_out, std_err = _ssh.exec_command(command)
            std_in.flush()
            _output = std_out.readlines()
            stdret = std_err.readlines()
            out_info = None
            out_error = None
            out_unknown = None
            if stdret:
                if (stdret[0]).split(':')[0] == 'INFO':
                    out_info = stdret
                elif (stdret[0]).split(':')[0] == 'ERROR':
                    out_error = stdret
                else:
                    out_unknown = stdret

            log.debug('_cli_ SSHClient: {!r} SSH_stdout:\n{}'.format(hostname, ''.join(_output)))
            log.info("SSH:: {} with command: {} - executed successfully".format(hostname, command))
            return dict(host=hostname, data=_output, info=out_info, error=out_error, unknown=out_unknown)
        finally:
            _ssh.close()
Exemple #23
0
 def __init__(self, host, user=None):
     """Connect to host honoring any user set configuration in ~/.ssh/config or /etc/ssh/ssh_config
     :type: str
     :param host: Hostname to connect to
     :type str:
     :param user: (Optional) User to login as. Defaults to logged in user or user from ~/.ssh/config if set
     :throws: paramiko.AuthenticationException on authentication error
     :throws: ssh_client.UnknownHostException on DNS resolution error
     :throws: ssh_client.ConnectionErrorException on error connecting"""
     ssh_config = paramiko.SSHConfig()
     _ssh_config_file = os.path.sep.join(
         [os.path.expanduser('~'), '.ssh', 'config'])
     # Load ~/.ssh/config if it exists to pick up username
     # and host address if set
     if os.path.isfile(_ssh_config_file):
         ssh_config.parse(open(_ssh_config_file))
     host_config = ssh_config.lookup(host)
     resolved_address = (host_config['hostname']
                         if 'hostname' in host_config else host)
     _user = host_config['user'] if 'user' in host_config else None
     if user:
         user = user
     else:
         user = _user
     client = paramiko.SSHClient()
     client.set_missing_host_key_policy(paramiko.MissingHostKeyPolicy())
     self.client = client
     self.channel = None
     self.user = user
     self.host = resolved_address
     self._connect()
Exemple #24
0
def initialize_connections(args):
    global connections
    global servers
    for server in servers:
        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(paramiko.MissingHostKeyPolicy())
        if server["pwd"] == "sshkey" and args.sshkey:
            try:
                client.connect(server["IP"],
                               username=server["user"],
                               key_filename=args.sshkey,
                               timeout=args.timeout)
            except (paramiko.ssh_exception.NoValidConnectionsError,
                    socket.timeout):
                logging.error("Could not connect to %s@%s" %
                              (server["user"], server["IP"]))
                continue
        else:
            if server["pwd"] == "sshkey" and not args.sshkey:
                logging.warning(
                    "sshkey defined as password but ssh key not provided!")
            try:
                client.connect(server["IP"],
                               username=server["user"],
                               password=server["pwd"],
                               timeout=args.timeout)
            except (paramiko.ssh_exception.NoValidConnectionsError,
                    socket.timeout):
                logging.error("Could not connect to %s@%s" %
                              (server["user"], server["IP"]))
                continue
        logging.debug("Unsetting HISTORY env in the ssh connection (" +
                      server["IP"] + ")")
        client.exec_command("unset HISTORY")
        connections.append([server, client])
Exemple #25
0
def executeSSHcommand_ACCEPT(server, login, password, command):
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(
        paramiko.MissingHostKeyPolicy())  # pas de check de clé
    client.connect(server, username=login, password=password)
    ssh_stdin, ssh_stdout, ssh_stderr = client.exec_command(command)
    client.close()
    return 0
Exemple #26
0
 def connect_to_host(self, host, username, password):
     self.ssh = paramiko.SSHClient()
     self.ssh.load_system_host_keys()
     self.ssh.set_missing_host_key_policy(paramiko.MissingHostKeyPolicy())
     self.ssh.connect(host,
                      username=username,
                      password=password,
                      timeout=10.0)
Exemple #27
0
    def _check(self):
        c = paramiko.SSHClient()
        c.set_missing_host_key_policy(paramiko.MissingHostKeyPolicy())  # ignore unknown hosts
        c.connect(hostname=str(self.target), username=self.username, password=self.password)
        stdin, stdout, stderr = c.exec_command('uname -a')
        evidence = stdout.readlines()[0]
        c.close()

        return evidence
 def connect(self):
     self.client = paramiko.SSHClient()
     self.client.set_missing_host_key_policy(
         paramiko.MissingHostKeyPolicy())
     self.client.connect(self.ip,
                         self.port,
                         username=YB_USERNAME,
                         key_filename=self.key_filename,
                         timeout=10)
Exemple #29
0
 def __init__(self):
     # self.default_xml_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), "server_config.xml")
     self.paramiko_log_file = os.path.join(os.path.dirname(__file__),
                                           "paramiko.log")
     self.set_paramiko_log_file()
     self.ssh = paramiko.SSHClient()
     self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
     self.ssh.set_missing_host_key_policy(paramiko.MissingHostKeyPolicy())
     self.version = "version 0.3"
Exemple #30
0
 def __init__(self, instance, username, key_filename, timeout=10):
     super(SSHClient, self).__init__()
     self.set_missing_host_key_policy(paramiko.MissingHostKeyPolicy())
     self.instance = instance
     self.username = username
     self.key_filename = key_filename
     self.ip = instance.private_ip_address
     self.name = instance.tags.get("Name")
     self.timeout = timeout