Python paramiko.AutoAddPolicy() Examples

The following are 30 code examples of paramiko.AutoAddPolicy(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module paramiko , or try the search function .
Example #1
Source File: docker.py    From pywren-ibm-cloud with Apache License 2.0 29 votes vote down vote up
def _ssh_run_remote_command(self, cmd):
        ssh_client = paramiko.SSHClient()
        ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh_client.connect(hostname=self.host,
                           username=self.config['ssh_user'],
                           password=self.config['ssh_password'])
        stdin, stdout, stderr = ssh_client.exec_command(cmd)

        out = stdout.read().decode().strip()
        error = stderr.read().decode().strip()
        if self.log_level:
            logger.info(out)
        if error:
            raise Exception('There was an error pulling the runtime: {}'.format(error))
        ssh_client.close()

        return out 
Example #2
Source File: ssh.py    From JetPack with Apache License 2.0 10 votes vote down vote up
def ssh_edit_file(adress, user, passw, remotefile, regex, replace):
        client = paramiko.SSHClient()
        client.load_system_host_keys()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        trans = paramiko.Transport((adress, 22))
        trans.connect(username=user, password=passw)
        sftp = paramiko.SFTPClient.from_transport(trans)
        f_in = sftp.file(remotefile, "r")
        c_in = f_in.read()
        pattern = re.compile(regex, re.MULTILINE | re.DOTALL)
        c_out = pattern.sub(replace, c_in)
        f_out = sftp.file(remotefile, "w")
        f_out.write(c_out)
        f_in.close()
        f_out.close()
        sftp.close()
        trans.close() 
Example #3
Source File: installInsightAgent.py    From InsightAgent with Apache License 2.0 9 votes vote down vote up
def sshInstall(retry,hostname):
    global user
    global password
    global userInsightfinder
    global licenseKey
    global samplingInterval
    global reportingInterval
    global agentType
    if retry == 0:
        print "Install Fail in", hostname
        q.task_done()
        return
    print "Start installing agent in", hostname, "..."
    try:
        s = paramiko.SSHClient()
        s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        if os.path.isfile(password) == True:
            s.connect(hostname, username=user, key_filename = password, timeout=60)
        else:
            s.connect(hostname, username=user, password = password, timeout=60)
        transport = s.get_transport()
        session = transport.open_session()
        session.set_combine_stderr(True)
        session.get_pty()
        session.exec_command("sudo rm -rf insightagent* InsightAgent* \n \
        wget --no-check-certificate https://github.com/insightfinder/InsightAgent/archive/master.tar.gz -O insightagent.tar.gz && \
        tar xzvf insightagent.tar.gz && \
        cd InsightAgent-master && deployment/checkpackages.sh -env\n")
        stdin = session.makefile('wb', -1)
        stdout = session.makefile('rb', -1)
        stdin.write(password+'\n')
        stdin.flush()
        session.recv_exit_status() #wait for exec_command to finish
        s.close()
        print "Install Succeed in", hostname
        q.task_done()
        return
    except paramiko.SSHException, e:
        print "Invalid Username/Password for %s:"%hostname , e
        return sshInstall(retry-1,hostname) 
Example #4
Source File: network.py    From LiMEaide with GNU General Public License v3.0 9 votes vote down vote up
def connect(self):
        """Call to set connection with remote client."""

        try:
            self.paramiko_session = paramiko.SSHClient()
            self.paramiko_session.set_missing_host_key_policy(
                paramiko.AutoAddPolicy())

            self.paramiko_session.connect(
                self.client.ip, username=self.client.user,
                password=self.client.pass_, key_filename=self.client.key,
                allow_agent=True, compress=self.client.compress)

        except (paramiko.AuthenticationException,
                paramiko.ssh_exception.NoValidConnectionsError) as e:
            self.logger.error(e)
            sys.exit(colored("> {}".format(e), 'red'))

        except paramiko.SSHException as e:
            self.logger.error(e)
            sys.exit(colored("> {}".format(e), 'red'))

        self.transfer = network.Network(
            self.paramiko_session, self.client.ip, self.client.port)
        self.transfer.open() 
Example #5
Source File: python多线程ssh爆破.py    From fuzzdb-collect with GNU General Public License v3.0 8 votes vote down vote up
def run(self):
        print("Start try ssh => %s" % self.ip)
        username = "root"
        try:
            password = open(self.dict).read().split('\n')
        except:
            print("Open dict file `%s` error" % self.dict)
            exit(1)
        for pwd in password:
            try:
                ssh = paramiko.SSHClient()
                ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                ssh.connect(self.ip, self.port, username, pwd, timeout = self.timeout)
                print("\nIP => %s, Login %s => %s \n" % (self.ip, username, pwd))
                open(self.LogFile, "a").write("[ %s ] IP => %s, port => %d, %s => %s \n" % (time.asctime( time.localtime(time.time()) ), self.ip, self.port, username, pwd))
                break
            except:
                print("IP => %s, Error %s => %s" % (self.ip, username, pwd))
                pass 
Example #6
Source File: ssh.py    From JetPack with Apache License 2.0 7 votes vote down vote up
def execute_command_readlines(address, usr, pwd, command):
        try:
            logger.debug("ssh " + usr + "@" + address + ", running : " +
                         command)
            client = paramiko.SSHClient()
            client.load_system_host_keys()
            client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

            client.connect(address, username=usr, password=pwd)
            _, ss_stdout, ss_stderr = client.exec_command(command)
            r_out, r_err = ss_stdout.readlines(), ss_stderr.read()
            logger.debug(r_err)
            if len(r_err) > 5:
                logger.error(r_err)
            else:
                logger.debug(r_out)
            client.close()
        except IOError:
            logger.warning(".. host " + address + " is not up")
            return "host not up", "host not up"

        return r_out, r_err 
Example #7
Source File: etss_ssh_in.py    From HPN-Scripting with MIT License 6 votes vote down vote up
def main():
    target_ip = etss_range(ip)
    print target_ip
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    for i in target_ip:
        try:
            ssh.connect(i, username=user, password=passwd)
            print "SSH connection established to %s" % (i)
            remote = ssh.invoke_shell()
            print "Interactive SSH session established"
            output = remote.recv(1000)
            print output
            #Disable pausing between screens of output
            screen_disable(remote)
            #Send commands to network device
            remote.send('\n')
            remote.send(cmd)
            time.sleep(2)
            output = remote.recv(5000)
            print output
        except:
            ssh.close()
            print "Problem connecting with ip: %s" % (i)
            continue 
Example #8
Source File: stopcron.py    From InsightAgent with Apache License 2.0 6 votes vote down vote up
def sshStopCron(retry,hostname):
    global user
    global password
    if retry == 0:
        print "Stop Cron Failed in", hostname
        q.task_done()
        return
    try:
        s = paramiko.SSHClient()
        s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        if os.path.isfile(password) == True:
            s.connect(hostname, username=user, key_filename = password, timeout=60)
        else:
            s.connect(hostname, username=user, password = password, timeout=60)
        transport = s.get_transport()
        session = transport.open_session()
        session.set_combine_stderr(True)
        session.get_pty()
        command = "sudo mv /etc/cron.d/ifagent InsightAgent-master/ifagent."+time.strftime("%Y%m%d%H%M%S")+"\n"
        session.exec_command(command)
        stdin = session.makefile('wb', -1)
        stdout = session.makefile('rb', -1)
        stdin.write(password+'\n')
        stdin.flush()
        session.recv_exit_status() #wait for exec_command to finish
        s.close()
        print "Stopped Cron in ", hostname
        q.task_done()
        return
    except paramiko.SSHException, e:
        print "Invalid Username/Password for %s:"%hostname , e
        return sshStopCron(retry-1,hostname) 
Example #9
Source File: aws_launcher.py    From CrypTen with MIT License 6 votes vote down vote up
def connect_to_instance(instance, keypath, username, http_proxy=None):
    print(f"Connecting to {instance.id}...")

    ip_address = instance.public_ip_address
    if http_proxy:
        # paramiko.ProxyCommand does not do string substitution for %h %p,
        # so 'nc --proxy-type http --proxy fwdproxy:8080 %h %p' would not work!
        proxy = paramiko.ProxyCommand(
            f"nc --proxy-type http --proxy {http_proxy} {ip_address} {22}"
        )
        proxy.settimeout(300)
    client = paramiko.SSHClient()
    client.load_system_host_keys()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    retries = 20
    while retries > 0:
        try:
            client.connect(
                ip_address,
                username=username,
                key_filename=keypath,
                timeout=10,
                sock=proxy if http_proxy else None,
            )
            print(f"Connected to {instance.id}")
            break
        except Exception as e:
            print(f"Exception: {e} Retrying...")
            retries -= 1
            time.sleep(10)
    return client 
Example #10
Source File: ssh_with_cmd.py    From hacker-scripts with MIT License 6 votes vote down vote up
def weak_pass(password, ip, port=22, timeout=5):
    for name in username_list:
        try:
            client = paramiko.SSHClient()
            client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            client.connect(ip, port, str(name), str(password), timeout=timeout)
            found_password.append((ip, password))
            logger.warning('[True ] %s %s:%s' % (ip, name, password))
            append_2_file('[True ] %s %s:%s' % (ip, name, password))
            try:
                reverse_shell_cmd(client)
                alter_password_cmd(client, password)
                logger.warning('修改密码成功 %s %s:%s' % (ip, name, new_password))
                append_2_file('修改密码成功 %s %s:%s' % (ip, name, new_password))
                new_password_success.append((ip, new_password))
            except Exception as ex:
                logger.info(ex)
                logger.warning('修改密码失败 %s %s' % (ip, name))
            return True
        except Exception as e:
            logger.info(e)
            logger.debug('[False] %s %s:%s' % (ip, name, new_password))

    return False 
Example #11
Source File: ssh.py    From aztk with MIT License 6 votes vote down vote up
def connect(hostname, port=22, username=None, password=None, pkey=None, timeout=None):
    import paramiko

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

    if pkey:
        ssh_key = paramiko.RSAKey.from_private_key(file_obj=io.StringIO(pkey))
    else:
        ssh_key = None

    timeout = timeout or 20
    logging.debug("Connecting to %s@%s:%d, timeout=%d", username, hostname, port, timeout)
    try:
        client.connect(hostname, port=port, username=username, password=password, pkey=ssh_key, timeout=timeout)
    except socket.timeout:
        raise AztkError("Connection timed out to: {}".format(hostname))

    return client 
Example #12
Source File: views.py    From chain with Apache License 2.0 6 votes vote down vote up
def taillog(request, hostname, port, username, password, private, tail):
    """
    执行 tail log 接口
    """
    channel_layer = get_channel_layer()
    user = request.user.username
    os.environ["".format(user)] = "true"
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    if password:
        ssh.connect(hostname=hostname, port=port, username=username, password=decrypt_p(password))
    else:
        pkey = paramiko.RSAKey.from_private_key_file("{0}".format(private))
        ssh.connect(hostname=hostname, port=port, username=username, pkey=pkey)
    cmd = "tail " + tail
    stdin, stdout, stderr = ssh.exec_command(cmd, get_pty=True)
    for line in iter(stdout.readline, ""):
        if os.environ.get("".format(user)) == 'false':
            break
        result = {"status": 0, 'data': line}
        result_all = json.dumps(result)
        async_to_sync(channel_layer.group_send)(user, {"type": "user.message", 'text': result_all}) 
Example #13
Source File: create_vm_full_script.py    From Hands-On-Enterprise-Automation-with-Python with MIT License 6 votes vote down vote up
def upload_and_create_directory(vm_name, hdd_size, source_file):
    commands = ["mkdir /vmfs/volumes/datastore1/{0}".format(vm_name),
                "vmkfstools -c {0}g -a lsilogic -d zeroedthick /vmfs/volumes/datastore1/{1}/{1}.vmdk".format(hdd_size,
                                                                                                             vm_name), ]
    register_command = "vim-cmd solo/registervm /vmfs/volumes/datastore1/{0}/{0}.vmx".format(vm_name)

    ipaddr = "10.10.10.115"
    username = "root"
    password = "access123"

    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    ssh.connect(ipaddr, username=username, password=password, look_for_keys=False, allow_agent=False)

    for cmd in commands:
        try:
            stdin, stdout, stderr = ssh.exec_command(cmd)
            print " DEBUG: ... Executing the command on ESXI server".format(str(stdout.readlines()))

        except Exception as e:
            print e
            pass
            print " DEBUG: **ERR....unable to execute command"
        time.sleep(2)
    with SCPClient(ssh.get_transport()) as scp:
        print(" DEBUG: ... Uploading file to the datastore")
        scp.put(source_file, remote_path='/vmfs/volumes/datastore1/{0}'.format(vm_name))
        print(" DEBUG: ... Register the virtual machine {}".format(vm_name))
        ssh.exec_command(register_command)

    ssh.close() 
Example #14
Source File: main.py    From crowbar with MIT License 6 votes vote down vote up
def sshlogin(self, ip, port, user, keyfile, timeout):
        try:
            ssh = paramiko.SSHClient()
            paramiko.util.log_to_file("/dev/null")
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        except:
            pass
        else:
            brute = "LOG-SSH: " + ip + ":" + str(port) + " - " + user + ":" + keyfile + ":" + str(timeout)
            self.logger.log_file(brute)

            try:
                ssh.connect(ip, port, username=user, password=None, pkey=None, key_filename=keyfile, timeout=timeout,
                            allow_agent=False, look_for_keys=False)
                result = bcolors.OKGREEN + "SSH-SUCCESS: " + bcolors.ENDC + bcolors.OKBLUE + ip + ":" + str(
                    port) + " - " + user + ":" + keyfile + bcolors.ENDC
                self.logger.output_file(result)
                Main.is_success = 1
            except:
                pass 
Example #15
Source File: ssh.py    From ARC with MIT License 6 votes vote down vote up
def _connect(self) -> Tuple[paramiko.sftp_client.SFTPClient, paramiko.SSHClient]:
        """
        Connect via paramiko, and open a SSH session as well as a SFTP session.

        Returns:
            Tuple[paramiko.sftp_client.SFTPClient, paramiko.SSHClient]:
                - An SFTP client used to perform remote file operations. 
                - A high-level representation of a session with an SSH server.
        """
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.load_system_host_keys(filename=self.key)
        try:
            # If the server accepts the connection but the SSH daemon doesn't respond in 
            # 15 seconds (default in paramiko) due to network congestion, faulty switches, 
            # etc..., common solution is to enlarging the timeout variable.
            ssh.connect(hostname=self.address, username=self.un, banner_timeout=200)
        except:
            # This sometimes gives "SSHException: Error reading SSH protocol banner[Error 104] Connection reset by peer"
            # Try again:
            ssh.connect(hostname=self.address, username=self.un, banner_timeout=200)
        sftp = ssh.open_sftp()
        return sftp, ssh 
Example #16
Source File: ssh_connection.py    From pynet with Apache License 2.0 6 votes vote down vote up
def establish_connection(ip, username='', password=''):
    '''
    Use Paramiko to establish an SSH channel to the device

    Must return both return_conn_pre and return_conn so that the SSH
    connection is not garbage collected

    '''

    remote_conn_pre = paramiko.SSHClient()
    remote_conn_pre.set_missing_host_key_policy(
        paramiko.AutoAddPolicy())

    remote_conn_pre.connect(ip, username=username, password=password,
                            look_for_keys=False, allow_agent=False)

    remote_conn = remote_conn_pre.invoke_shell()

    # Clear banner and prompt
    output = remote_conn.recv(65535)

    return (remote_conn_pre, remote_conn, output) 
Example #17
Source File: oxfs.py    From oxfs with MIT License 5 votes vote down vote up
def open_sftp(self):
        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        client.load_system_host_keys()
        client.connect(self.host, port=self.port, username=self.user)
        return client, client.open_sftp(); 
Example #18
Source File: arubaos_cx_ssh_cli.py    From aruba-switch-ansible with Apache License 2.0 5 votes vote down vote up
def __init__(self, module):
        """
        Init all variables and starts login
        :param module: module objects itself
        """
        # Init Vars
        args = module.params

        # List of strings of CLI Commands
        paramiko_ssh_connection_args = {'hostname': args['ip'], 'port': args['port'], 'username': args['user'],
                                        'password': args['password'], 'look_for_keys': args['look_for_keys'],
                                        'allow_agent': args['allow_agent'], 'key_filename': args['key_filename'],
                                        'timeout': args['timeout']}
        self.module = module

        # Login
        self.ssh_client = paramiko.SSHClient()
        # Default AutoAdd as Policy
        self.ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        # Connect to Switch via SSH
        self.ssh_client.connect(**paramiko_ssh_connection_args)
        self.prompt = ''
        # SSH Command execution not allowed, therefor using the following paramiko functionality
        self.shell_chanel = self.ssh_client.invoke_shell()
        self.shell_chanel.settimeout(8)
        # AOS-CX specific
        self.get_prompt() 
Example #19
Source File: ssh_connection.py    From pynet with Apache License 2.0 5 votes vote down vote up
def establish_connection(self):
        '''
        Establish SSH connection to the network device
        '''

        VERBOSE = False

        if VERBOSE:
            print "#" * 80

        # Create instance of SSHClient object
        self.remote_conn_pre = paramiko.SSHClient()

        # Automatically add untrusted hosts (make sure okay for security policy in your environment)
        self.remote_conn_pre.set_missing_host_key_policy(
            paramiko.AutoAddPolicy())

        # initiate SSH connection
        print "SSH connection established to {}:{}".format(self.ip, self.port)
        self.remote_conn_pre.connect(hostname=self.ip, port=self.port,
                                     username=self.username, password=self.password,
                                     look_for_keys=False, allow_agent=False)

        # Use invoke_shell to establish an 'interactive session'
        self.remote_conn = self.remote_conn_pre.invoke_shell()
        print "Interactive SSH session established"

        # Strip the initial router prompt
        time.sleep(3)
        output = self.remote_conn.recv(MAX_BUFFER)

        self.disable_paging()

        if VERBOSE:
            print output
            print "#" * 80
            print 
Example #20
Source File: ssh_connection.py    From pynet with Apache License 2.0 5 votes vote down vote up
def establish_connection(self):
        '''
        Establish SSH connection to the network device
        '''

        verbose = False

        if verbose:
            print "#" * 80

        # Create instance of SSHClient object
        self.remote_conn_pre = paramiko.SSHClient()

        # Automatically add untrusted hosts (make sure okay for security policy in your environment)
        self.remote_conn_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        # initiate SSH connection
        print "SSH connection established to {}:{}".format(self.ip, self.port)
        self.remote_conn_pre.connect(hostname=self.ip, port=self.port,
                                     username=self.username, password=self.password,
                                     look_for_keys=False, allow_agent=False)

        # Use invoke_shell to establish an 'interactive session'
        self.remote_conn = self.remote_conn_pre.invoke_shell()
        print "Interactive SSH session established"

        # Strip the initial router prompt
        time.sleep(3)
        output = self.remote_conn.recv(MAX_BUFFER)

        self.disable_paging()

        if verbose:
            print output
            print "#" * 80
            print 
Example #21
Source File: ssh_connection.py    From pynet with Apache License 2.0 5 votes vote down vote up
def establish_connection(self):
        '''
        Establish SSH connection to the network device
        '''

        verbose = False

        if verbose:
            print "#" * 80

        # Create instance of SSHClient object
        self.remote_conn_pre = paramiko.SSHClient()

        # Automatically add untrusted hosts (make sure okay for security policy in your environment)
        self.remote_conn_pre.set_missing_host_key_policy(
            paramiko.AutoAddPolicy())

        # initiate SSH connection
        print "SSH connection established to {}:{}".format(self.ip, self.port)
        self.remote_conn_pre.connect(hostname=self.ip, port=self.port,
                                     username=self.username, password=self.password,
                                     look_for_keys=False, allow_agent=False)

        # Use invoke_shell to establish an 'interactive session'
        self.remote_conn = self.remote_conn_pre.invoke_shell()
        print "Interactive SSH session established"

        # Strip the initial router prompt
        time.sleep(3)
        output = self.remote_conn.recv(MAX_BUFFER)

        self.disable_paging()

        if verbose:
            print output
            print "#" * 80
            print 
Example #22
Source File: ssh.py    From CrackMapExec with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def create_conn_obj(self):
        self.conn = paramiko.SSHClient()
        self.conn.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        try:
            self.conn.connect(self.host, port=self.args.port)
        except AuthenticationException:
            return True
        except SSHException:
            return True
        except NoValidConnectionsError:
            return False
        except socket.error:
            return False 
Example #23
Source File: paramiko_proxy.py    From DShell with GNU General Public License v3.0 5 votes vote down vote up
def getchannel(key,id):
    if key in connected_channels:
        channel = connected_channels[key][1]
    else:
        host = models.Host.objects.get(pk=id)
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(host.addr,host.port,host.username,host.password)
        channel = ssh.invoke_shell()
        channel.setblocking(0)
        glock.acquire()
        connected_channels[key] = [ssh,channel]
        glock.release()
    return channel 
Example #24
Source File: vpn_utils.py    From neutron-vpnaas with Apache License 2.0 5 votes vote down vote up
def execute_cmd_over_ssh(host, cmd, private_key):
    """Run the given command over ssh

    Using paramiko package, it creates a connection to the given host;
    executes the required command on it and returns the output.
    :param host: Dictionary of ip, username and password
    :param cmd: Command to be run over ssh
    :param private_key: path to private key file
    :return: Output of the executed command
    """
    LOG.debug('EXECUTE COMMAND <%s> OVER SSH', cmd)
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    k = paramiko.RSAKey.from_private_key_file(private_key)

    try:

        client.connect(host["ip"], username=host["username"], pkey=k)
    except paramiko.BadHostKeyException as e:
        raise Exception(
            "BADHOSTKEY EXCEPTION WHEN CONNECTING TO %s", host["ip"], e)
    except paramiko.AuthenticationException as e:
        raise Exception(
            "AUTHENTICATION EXCEPTION WHEN CONNECTING TO %s", host["ip"], e)
    except paramiko.SSHException as e:
        raise Exception("SSH EXCEPTION WHEN CONNECTING TO %s", host["ip"], e)
    except socket.error as e:
        raise Exception("SOCKET ERROR WHEN CONNECTING TO %s", host["ip"], e)
    LOG.debug("CONNECTED TO HOST <%s>", host["ip"])
    try:
        stdin, stdout, stderr = client.exec_command(cmd)
        return stdout.read().splitlines()
    except paramiko.SSHException as e:
        raise Exception("SSHEXCEPTION WHEN CONNECTING TO %s", host["ip"], e)
    finally:
        client.close() 
Example #25
Source File: ssh.py    From KubeOperator with Apache License 2.0 5 votes vote down vote up
def run_cmd(self, cmd):
        client = paramiko.SSHClient()
        try:
            client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            client.connect(
                self.config.host,
                self.config.port,
                self.config.username,
                self.config.password,
                key_filename=create_ssh_key(self.config.private_key)
            )
            session = client.get_transport().open_session()
            session.exec_command(cmd)
            while not session.exit_status_ready():
                time.sleep(0.5)
            exit_code = session.recv_exit_status()
            if exit_code == 0:
                result = session.recv(4096 * 1024).decode(encoding='UTF-8', errors='strict').rstrip("\n")
            else:
                result = session.recv_stderr(4096 * 1024).decode(encoding='UTF-8', errors='strict').rstrip("\n")
            return result, exit_code
        except SSHException as e:
            print("[%s] %s target failed, the reason is %s" % (datetime.datetime.now(), self.config.host, str(e)))
        finally:
            client.close() 
Example #26
Source File: hive.py    From marvin-python-toolbox with Apache License 2.0 5 votes vote down vote up
def _get_ssh_client(self, hdfs_host, hdfs_port, username, password):
        ssh = SSHClient()
        ssh.set_missing_host_key_policy(AutoAddPolicy())
        ssh.connect(hostname=hdfs_host, port=hdfs_port, username=username, password=password, )
        return ssh 
Example #27
Source File: ssh.py    From Cloud99 with Apache License 2.0 5 votes vote down vote up
def __init__(self, host, user, password):
        self.host = host
        self.user = user
        self.password = password
        self.client = paramiko.SSHClient()
        self.client.load_system_host_keys()
        self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 
Example #28
Source File: utils.py    From pytos with Apache License 2.0 5 votes vote down vote up
def get_ssh_client(host, username, password=None, keyfile=None):
    """
    Returns a connected ssh client using either a password or a keyfile
     :param str host: ip of remote host
     :param str username:
     :param str password:
     :param str keyfile: path to local public key file
     :return: A connected ssh client
     :rtype: paramiko.SSHClient
     :raises: ValueError, PermissionError, ConnectionRefusedError
    """
    logger.info("Creating SSH connection to '{}' with user '{}'.".format(host, username))
    ssh_client = paramiko.SSHClient()
    ssh_client.load_system_host_keys()
    ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    try:
        if keyfile:
            ssh_client.connect(host, username=username, key_filename=keyfile)
        elif password:
            ssh_client.connect(host, username=username, password=password, look_for_keys=False)
        else:
            ssh_client.close()
            raise ValueError('Either password or keyfile must be passed to get_ssh_client.')
    except paramiko.ssh_exception.AuthenticationException:
        ssh_client.close()
        raise PermissionError('Incorrect credentials for host {}'.format(host))
    except (paramiko.ssh_exception.SSHException, socket_error) as ex:
        ssh_client.close()
        raise ConnectionRefusedError('Could not connect to host {}, error:\n{}'.format(host, str(ex)))
    logger.info('Successfully connected to {}'.format(host))
    return ssh_client 
Example #29
Source File: remote_shell.py    From margaritashotgun with MIT License 5 votes vote down vote up
def connect(self, auth, address, port, jump_host, jump_auth):
        """
        Creates an ssh session to a remote host

        :type auth: :py:class:`margaritashotgun.auth.AuthMethods`
        :param auth: Authentication object
        :type address: str
        :param address: remote server address
        :type port: int
        :param port: remote server port
        """

        try:
            self.target_address = address
            sock = None
            if jump_host is not None:
                self.jump_host_ssh = paramiko.SSHClient()
                self.jump_host_ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                self.connect_with_auth(self.jump_host_ssh, jump_auth,
                                       jump_host['addr'], jump_host['port'], sock)
                transport = self.jump_host_ssh.get_transport()
                dest_addr = (address, port)
                jump_addr = (jump_host['addr'], jump_host['port'])
                channel = transport.open_channel('direct-tcpip', dest_addr,
                                                 jump_addr)
                self.connect_with_auth(self.ssh, auth, address, port, channel)
            else:
                self.connect_with_auth(self.ssh, auth, address, port, sock)
        except (AuthenticationException, SSHException,
                ChannelException, SocketError) as ex:
            raise SSHConnectionError("{0}:{1}".format(address, port), ex) 
Example #30
Source File: arubaos_switch_ssh_cli.py    From aruba-switch-ansible with Apache License 2.0 5 votes vote down vote up
def __init__(self, module):
        """
        Init all variables and starts login
        :param module: module objects itself
        """
        # Init Vars
        args = module.params
        # List of strings of CLI Commands
        paramiko_ssh_connection_args = {'hostname': args['ip'], 'port': args['port'], 'username': args['user'],
                                        'password': args['password'], 'look_for_keys': args['look_for_keys'],
                                        'allow_agent': args['allow_agent'], 'key_filename': args['key_filename'],
                                        'timeout': args['timeout']}
        self.module = module

        # Login
        self.ssh_client = paramiko.SSHClient()
        # Default AutoAdd as Policy
        self.ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        # Connect to Switch via SSH
        self.ssh_client.connect(**paramiko_ssh_connection_args)
        self.prompt = ''
        # SSH Command execution not allowed, therefor using the following paramiko functionality
        self.shell_chanel = self.ssh_client.invoke_shell()
        self.shell_chanel.settimeout(8)
        # AOS-Switch specific
        self.additional_connection_setup()