in ebcli/operations/sshops.py [0:0]
def ssh_into_instance(instance_id, keep_open=False, force_open=False, custom_ssh=None, command=None):
instance = ec2.describe_instance(instance_id)
try:
keypair_name = instance['KeyName']
except KeyError:
raise NoKeypairError()
try:
ip = instance['PublicIpAddress']
except KeyError:
if 'PrivateIpAddress' in instance:
ip = instance['PrivateIpAddress']
else:
raise NotFoundError(strings['ssh.noip'])
security_groups = instance['SecurityGroups']
user = 'ec2-user'
ssh_group = None
has_restriction = False
rule_existed_before = False
group_id = None
for group in security_groups:
group_id = group['GroupId']
group = ec2.describe_security_group(group_id)
for permission in group.get('IpPermissions', []):
if permission.get('ToPort', None) == 22:
ssh_group = group_id
for rng in permission.get('IpRanges', []):
ip_restriction = rng.get('CidrIp', None)
if ip_restriction is not None:
if ip_restriction != '0.0.0.0/0':
has_restriction = True
elif ip_restriction == '0.0.0.0/0':
rule_existed_before = True
if has_restriction and not force_open:
io.log_warning(strings['ssh.notopening'])
elif group_id and not rule_existed_before:
io.echo(strings['ssh.openingport'])
ec2.authorize_ssh(ssh_group or group_id)
io.echo(strings['ssh.portopen'])
try:
if custom_ssh:
custom_ssh = custom_ssh.split()
else:
ident_file = _get_ssh_file(keypair_name)
custom_ssh = ['ssh', '-i', ident_file, '-o', 'IdentitiesOnly yes']
custom_ssh.extend([user + '@' + ip])
if command:
custom_ssh.extend(command.split())
io.echo('INFO: Running ' + ' '.join(custom_ssh))
returncode = subprocess.call(custom_ssh)
if returncode != 0:
LOG.debug(custom_ssh[0] + ' returned exitcode: ' + str(returncode))
raise CommandError('An error occurred while running: ' + custom_ssh[0] + '.')
except OSError:
CommandError(strings['ssh.notpresent'])
finally:
if keep_open:
pass
elif (not has_restriction or force_open) and group_id and not rule_existed_before:
ec2.revoke_ssh(ssh_group or group_id)
io.echo(strings['ssh.closeport'])