我有一个 shell 脚本,它运行一个 python 脚本来返回一个 AWS IP,然后应该通过 ssh 进入该 IP。很简单:
DNS=$(python ssh_into_master.py)
ssh $DNS
它按预期运行命令,但连接被拒绝。
> ssh -i /path/to/key.pem.txt [email protected]
> ssh: connect to host the.ip.i.returned port 22: Connection refused
但是,如果我手动输入完全相同的命令,连接就会被接受。为什么当 ssh 命令的参数是动态生成时,连接会被拒绝?我以为这可能是密钥文件的权限问题,但是 shell 脚本是由创建密钥的同一用户运行的,所以它不应该具有相同的权限吗?
编辑:
这是 Python 脚本的净化版本。
# This script gets the public dns for the master ec2 instance in an auto-scaling group
import boto3
import sys
import time
autoscaling = boto3.client('autoscaling')
ec2 = boto3.client('ec2')
def get_dns(instance_id):
# IF THE INSTANCE IS NOT YET CREATED, WAIT 10s AND TRY AGAIN
status = ec2.describe_instance_status(InstanceIds=[instance_id])
if len(status['InstanceStatuses']) == 0:
time.sleep(10)
get_dns(instance_id)
return
status = status['InstanceStatuses'][0]['InstanceState']['Name']
# IF THE INSTANCE IS PENDING BUT NOT YET RUNNING, WAIT 15s AND TRY AGAIN
if status != 'running':
time.sleep(15)
get_dns(instance_id)
return
dns = ec2.describe_instances(InstanceIds=[instance_id])
dns = dns['Reservations'][0]['Instances'][0]['PublicDnsName']
dns = dns.split('.compute')[0].replace('-', '.')[4:]
print ' -i /path/to/key.pem.txt' \
' ec2-user@%s' % dns
def main():
groups_list = autoscaling.describe_auto_scaling_groups()['AutoScalingGroups']
# find the master group
for group in groups_list:
if group['LaunchConfigurationName'] == 'master':
if not group['Instances']:
# the group hasn't been launched yet, so wait 5 seconds
time.sleep(5)
main()
else:
instance_id = group['Instances'][0]['InstanceId']
get_dns(instance_id)
main()