How to use the paramiko.SSHClient function in paramiko

To help you get started, we’ve selected a few paramiko examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github iterative / dvc / tests / func / test_repro.py View on Github external
def write(self, bucket, key, body):
        path = posixpath.join(self._dir, key)

        ssh = paramiko.SSHClient()
        ssh.load_system_host_keys()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect("127.0.0.1")

        sftp = ssh.open_sftp()
        try:
            sftp.stat(path)
            sftp.remove(path)
        except IOError:
            pass

        stdin, stdout, stderr = ssh.exec_command(
            "mkdir -p $(dirname {})".format(path)
        )
        self.assertEqual(stdout.channel.recv_exit_status(), 0)
github couchbaselabs / mobile-testkit / keywords / remoteexecutor.py View on Github external
def __init__(self, host, sg_platform="centos", username=None, password=None):
        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.client = client
        self.host = host
        self.sg_platform = sg_platform
        if "[" in self.host:
            self.host = self.host.replace("[", "")
            self.host = self.host.replace("]", "")
        self.username = ansible.constants.DEFAULT_REMOTE_USER
        if username is not None:
            self.username = username
            self.password = password
github rongoro / clusto / contrib / sysinfo.py View on Github external
def discover_hardware(ip):
    client = SSHClient()

    client.load_system_host_keys()
    client.set_missing_host_key_policy(SilentPolicy())
    client.connect(ip, username='root', timeout=2.0)
    stdout = client.exec_command('cat /proc/partitions')[1].read()

    disks = []
    for line in stdout.split('\n'):
        if not line: continue
        line = [x for x in line.split(' ') if x]
        if not line[0].isdigit(): continue
        if not re.match('^sd[a-z]$', line[3]): continue
        name = line[3]
        blocks = int(line[2])
        blocks *= 1024
github VIDA-NYU / reprozip / reprounzip-vagrant / reprounzip / unpackers / vagrant / __init__.py View on Github external
key_file = Path('~/.vagrant.d/insecure_private_key').expand_user()
    info = dict(hostname=vagrant_info.get('hostname', '127.0.0.1'),
                port=int(vagrant_info.get('port', 2222)),
                username=vagrant_info.get('user', 'vagrant'),
                key_filename=key_file)
    logger.debug("SSH parameters from Vagrant: %s@%s:%s, key=%s",
                 info['username'], info['hostname'], info['port'],
                 info['key_filename'])

    unpacked_info = read_dict(target)
    use_chroot = unpacked_info['use_chroot']
    gui = unpacked_info['gui']

    if use_chroot:
        # Mount directories
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(IgnoreMissingKey())
        ssh.connect(**info)
        chan = ssh.get_transport().open_session()
        chan.exec_command(
            '/usr/bin/sudo /bin/sh -c %s' % shell_escape(
                'if ! grep -q "/experimentroot/dev " /proc/mounts; then '
                'mount -o rbind /dev /experimentroot/dev; '
                'fi; '
                'if ! grep -q "/experimentroot/proc " /proc/mounts; then '
                'mount -t proc none /experimentroot/proc; '
                'fi'))
        if chan.recv_exit_status() != 0:
            logger.critical("Couldn't mount directories in chroot")
            sys.exit(1)
        if gui:
            # Mount X11 socket
github hms-dbmi / hail-on-AWS-spot-instances / src / EMR_deploy_and_install_spot.py View on Github external
print('\nClusterId: '+cluster_id+'\n')

# Copy the key into the master
command='scp -o \'StrictHostKeyChecking no\' -i '+c['config']['PATH_TO_KEY']+c['config']['KEY_NAME']+'.pem '+c['config']['PATH_TO_KEY']+c['config']['KEY_NAME']+'.pem hadoop@'+master_dns+':/home/hadoop/.ssh/id_rsa'
os.system(command)
print('Copying keys...')

# Copy the installation script into the master
command='scp -o \'StrictHostKeyChecking no\' -i '+c['config']['PATH_TO_KEY']+c['config']['KEY_NAME']+'.pem '+PATH+'/install_hail_and_python36.sh hadoop@'+master_dns+':/home/hadoop'
os.system(command)

print('Installing software...')
print('Allow 4-8 minutes for full installation')
print('\n This is your Jupyter Lab link: '+ master_IP+':8192\n')
key = paramiko.RSAKey.from_private_key_file(c['config']['PATH_TO_KEY']+c['config']['KEY_NAME']+'.pem')
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname=master_IP, username="hadoop", pkey=key)

# Execute a command(cmd) after connecting/ssh to an instance
VERSION=c['config']['HAIL_VERSION']
command='./install_hail_and_python36.sh -v '+ VERSION
stdin, stdout, stderr = client.exec_command('cd /home/hadoop/')
stdin, stdout, stderr = client.exec_command(command)

# close the client connection
client.close()
github fmenabe / python-unix / unix / hosts.py View on Github external
self.ipv6 = ip
            self.fqdn = self._get_fqdn()
            self.ipv4 = self._get_ipv4()
        else:
            self.fqdn = ip
            self.ipv4 = self._get_ipv4()
            self.ipv6 = self._get_ipv6()
            self.fqdn = self._get_fqdn()

        if not self.ipv4 and not self.ipv6:
            raise ConnectError("no IPv4 or IPv6 address")

        self.ip = self.ipv6 if self.ipv6 and ipv6 else self.ipv4

        try:
            self.ssh = paramiko.SSHClient()
            self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            if password:
                self.ssh.connect(
                    self.ip,
                    username=username,
                    password=password,
                    allow_agent=False,
                    look_for_keys=False,
                    timeout=timeout
                )
            else:
                self.ssh.connect(
                    self.ip,
                    username=username,
                    timeout=timeout
                )
github openstack / cinder / cinder / volume / san.py View on Github external
def _connect_to_ssh(self):
        ssh = paramiko.SSHClient()
        #TODO(justinsb): We need a better SSH key policy
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        if FLAGS.san_password:
            ssh.connect(FLAGS.san_ip,
                        port=FLAGS.san_ssh_port,
                        username=FLAGS.san_login,
                        password=FLAGS.san_password)
        elif FLAGS.san_private_key:
            privatekeyfile = os.path.expanduser(FLAGS.san_private_key)
            # It sucks that paramiko doesn't support DSA keys
            privatekey = paramiko.RSAKey.from_private_key_file(privatekeyfile)
            ssh.connect(FLAGS.san_ip,
                        port=FLAGS.san_ssh_port,
                        username=FLAGS.san_login,
                        pkey=privatekey)
        else:
github Yenthe666 / auto_backup / auto_backup / models / db_backup.py View on Github external
# Check if there is a success or fail and write messages
        message_title = ""
        message_content = ""
        error = ""
        has_failed = False

        for rec in self:
            path_to_write_to = rec.sftp_path
            ip_host = rec.sftp_host
            port_host = rec.sftp_port
            username_login = rec.sftp_user
            password_login = rec.sftp_password

            # Connect with external server over SFTP, so we know sure that everything works.
            try:
                s = paramiko.SSHClient()
                s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                s.connect(ip_host, port_host, username_login, password_login, timeout=10)
                sftp = s.open_sftp()
                message_title = _("Connection Test Succeeded!\nEverything seems properly set up for FTP back-ups!")
            except Exception as e:
                _logger.critical('There was a problem connecting to the remote ftp: ' + str(e))
                error += str(e)
                has_failed = True
                message_title = _("Connection Test Failed!")
                if len(rec.sftp_host) < 8:
                    message_content += "\nYour IP address seems to be too short.\n"
                message_content += _("Here is what we got instead:\n")
            finally:
                if s:
                    s.close()
github xoolive / traffic / traffic / data / adsb / opensky_impala.py View on Github external
def _connect(self) -> None:  # coverage: ignore
        if self.username == "" or self.password == "":
            raise RuntimeError("This method requires authentication.")
        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        extra_args = dict()

        if self.proxy_command != "":
            # for instance:
            #    "ssh -W data.opensky-network.org:2230 proxy_machine"
            # or "connect.exe -H proxy_ip:proxy_port %h %p"
            logging.info(f"Using ProxyCommand: {self.proxy_command}")
            extra_args["sock"] = paramiko.ProxyCommand(self.proxy_command)

        client.connect(
            "data.opensky-network.org",
            port=2230,
            username=self.username,
            password=self.password,
            look_for_keys=False,