Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def _test_connection(self, **kwargs):
"""
(Most) kwargs get passed directly into SSHClient.connect().
The exception is ... no exception yet
"""
host_key = paramiko.RSAKey.from_private_key_file('tests/test_rsa.key')
public_host_key = paramiko.RSAKey(data=host_key.asbytes())
self.tc = paramiko.SSHClient()
self.tc.set_missing_host_key_policy(paramiko.WarningPolicy())
self.tc.get_host_keys().add('[%s]:%d' % (self.addr, self.port),
'ssh-rsa', public_host_key)
self.tc.connect(hostname=self.addr, port=self.port, username=self.username, gss_host=self.hostname,
gss_auth=True, **kwargs)
self.event.wait(1.0)
self.assert_(self.event.is_set())
self.assert_(self.ts.is_active())
self.assertEquals(self.username, self.ts.get_username())
self.assertEquals(True, self.ts.is_authenticated())
stdin, stdout, stderr = self.tc.exec_command('yes')
schan = self.ts.accept(1.0)
schan.send('Hello there.\n')
schan.send_stderr('This is on stderr.\n')
def get_proxmox_ssh(proxmox):
proxmox_ssh = SSHClient()
proxmox_ssh.set_missing_host_key_policy(WarningPolicy())
proxmox_ssh.connect(proxmox['host'],
username=proxmox['user'].split('@')[0])
return proxmox_ssh
def connect(self):
log.info("Connecting to Ubiquity mfi %s@%s:%d",
self.username, self.hostname, self.sshport)
self.client = SSHClient()
self.client.load_system_host_keys()
if self.verify_hostkey:
self.client.set_missing_host_key_policy(RejectPolicy())
else:
self.client.set_missing_host_key_policy(WarningPolicy())
self.client.connect(hostname=self.hostname, port=self.sshport,
username=self.username, password=self.password)
def get_conversation(self):
conversation = paramiko.SSHClient()
conversation.set_missing_host_key_policy(paramiko.WarningPolicy())
try:
conversation.connect( self.domain,
port=self.port,
username=self.username,
password=self.password)
except socket.gaierror , e :
raise SocksRemoteException, '链接代理失败'
except paramiko.AuthenticationException, e:
raise SocksRemoteException, '用户认证失败'
except paramiko.BadHostKeyException, e:
raise SocksRemoteException, 'Host Key 验证失败'
return conversation
InstanceIds=[self.helper_instance['InstanceId']]
)['Reservations'][0]['Instances'][0]
instance_ip = instance.get('PublicIpAddress')
if self.use_private_ip:
instance_ip = instance.get('PrivateIpAddress')
if self.verbose:
print('. ', end=' ')
sys.stdout.flush()
if timeout_counter * self.default_sleep >= self.ssh_timeout:
msg = 'Unable to obtain the instance IP address'
raise EC2UploadImgException(msg)
timeout_counter += 1
if self.verbose:
print()
client = paramiko.client.SSHClient()
client.set_missing_host_key_policy(paramiko.WarningPolicy())
if self.verbose:
print('Attempt ssh connection')
ssh_connection = None
timeout_counter = 1
while not ssh_connection:
try:
ssh_connection = client.connect(
key_filename=self.ssh_key_private_key_file,
username=self.inst_user_name,
hostname=instance_ip
)
except:
if self.verbose:
print('. ', end=' ')
sys.stdout.flush()
time.sleep(self.default_sleep)
def _wait_for_ssh(self, instance):
"""
Keeps retrying an SSH connection until it succeeds, then closes the
connection and returns.
"""
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.WarningPolicy())
times = 0
wait = 2
while times < 120/wait:
try:
key = self.key_file and self.key_file.name or env.key_filename
user = self.user and self.user or env.user
ssh.connect(getattr(instance, getattr(env, 'ec2_attr_for_ssh', 'public_dns_name')),
allow_agent=False, look_for_keys=False, username=user,
key_filename=key, timeout=self.ssh_timeout)
break
except (EOFError, socket.error, paramiko.SSHException) as e:
logger.debug('Error connecting ({0}); retrying in {1} '
'seconds'.format(e, wait))
times += 1
time.sleep(wait)
ssh.close()
else:
base_dir = '/home/%s' % username
auth_key = join(base_dir, '.ssh/authorized_keys')
# prior to creating ssh connection via paramiko, lets verify the public
# key supplied exists on disk
if isfile(public_key):
module.log('SSH public key %s exists!' % public_key)
else:
result['message'] = 'Unable to locate ssh public key %s' % public_key
module.fail_json(msg=result['message'])
module.exit_json(**result)
# create ssh client via paramiko
ssh_con = paramiko.SSHClient()
ssh_con.set_missing_host_key_policy(paramiko.WarningPolicy())
# connect to remote system
try:
ssh_con.connect(
hostname=hostname,
username=username,
password=password,
look_for_keys=False,
allow_agent=False,
port=port
)
except (paramiko.BadHostKeyException, paramiko.AuthenticationException,
paramiko.SSHException, socket.error) as ex:
result['message'] = ex
module.fail_json(msg='Connection failed to %s' % hostname, **result)
module.exit_json(**result)
# get username
if username == '':
default_username = getpass.getuser()
username = input('Username [%s]: ' % default_username)
if len(username) == 0:
username = default_username
if not UseGSSAPI or (not UseGSSAPI and not DoGSSAPIKeyExchange):
password = getpass.getpass('Password for %s@%s: ' % (username, hostname))
# now, connect and use paramiko Client to negotiate SSH2 across the connection
try:
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.WarningPolicy())
print('*** Connecting...')
if not UseGSSAPI or (not UseGSSAPI and not DoGSSAPIKeyExchange):
client.connect(hostname, port, username, password)
else:
# SSPI works only with the FQDN of the target host
hostname = socket.getfqdn(hostname)
try:
client.connect(hostname, port, username, gss_auth=UseGSSAPI,
gss_kex=DoGSSAPIKeyExchange)
except Exception:
password = getpass.getpass('Password for %s@%s: ' % (username, hostname))
client.connect(hostname, port, username, password)
chan = client.invoke_shell()
print(repr(client.get_transport()))
print('*** Here we go!\n')
def scp_upload(src_blob='Preproc.tar.gz', dst_blob="~", options={'hostname': 'lecun', 'username': 'shawley'}, progress=simple_callback):
# from https://gist.github.com/acdha/6064215
#--- Make the Paramiko SSH thing use my .ssh/config file (b/c I like ProxyCommand!)
client = SSHClient()
client.load_system_host_keys()
client._policy = WarningPolicy()
client.set_missing_host_key_policy(WarningPolicy()) # hmm. WarningPolicy? Most people use AutoAddPolicy.
ssh_config = 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': options['hostname'], 'username': options["username"]}
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'] = ProxyCommand(user_config['proxycommand'])
Parameters
----------
hostname: str
Hostname to connect to.
username: str
Username to connect as.
prompt_for_password: boolean
Prompt for password for unopen keys. If False, will raise an exception
if no valid open key is found.
Returns
-------
paramiko ssh instance.
"""
ssh = SSHClient()
ssh.set_missing_host_key_policy(WarningPolicy())
try:
ssh.connect(hostname, username=username)
except PasswordRequiredException:
if not prompt_for_password:
raise
password = getpass("SSH Private Key password: ")
ssh.connect(hostname, username=username, password=password)
def command(self, command, raise_on_error=True):
chan = self._transport.open_session()
chan.exec_command(command)
stdout = chan.makefile('r').read()
stderr = chan.makefile_stderr('r').read()
status = chan.recv_exit_status()
if status != 0: