LoginSignup
1
1

More than 5 years have passed since last update.

ec2ssh updateで生成されたホスト名に連番を割り振る

Last updated at Posted at 2016-09-12

ec2ssh updateで生成されたホスト名に連番を割り振る

説明

下記のプログラムを実行すると、ec2ssh updateを実行して、~/.ssh/config の中に同じ名前のインスタンスがあったら連番を振ってくれます。
python 2.7.10で動作確認。

下のような感じで書き換えてくれます。

Host ec2instance
    ...

Host ec2instance
    ...

Host ec2instance
    ...

Host ec2instance
    ...

Host ec2instance2
    ...

Host ec2instance3
    ...

ソース

#! /usr/bin/env python
#-*- coding: utf-8 -*-

import io           # input/output
import subprocess   # コマンド実行
import re           # 正規表現
import os
from datetime import datetime

import sys

# Trueでec2sshや保存操作を行わない
DEBUG = False

# confirm
def query_yes_no(question, default="yes"):
    valid = {"yes": True, "y": True, "ye": True,
             "no": False, "n": False}
    if default is None:
        prompt = " [y/n] "
    elif default == "yes":
        prompt = " [Y/n] "
    elif default == "no":
        prompt = " [y/N] "
    else:
        raise ValueError("invalid default answer: '%s'" % default)

    while True:
        sys.stdout.write(question + prompt)
        choice = raw_input().lower()
        if default is not None and choice == '':
            return valid[default]
        elif choice in valid:
            return valid[choice]
        else:
            sys.stdout.write("Please respond with 'yes' or 'no' "
                             "(or 'y' or 'n').\n")

# データ内容を読込む
def read_content(filePath):
    f = io.open(filePath, mode='r', encoding='utf-8')
    content = f.read()
    f.close()
    return content

# データ内容を上書き
def save_content(filePath, data):
    f = io.open(filePath, mode='w', encoding='utf-8')
    content = f.write(data)
    f.close()

# ホスト名を書き換える
def renameHostName(v):
    hostName = v.group()

    if hostName in hostsDict:
        # ホスト名が重複している場合
        hostsDict[hostName]['num'] += 1
        hostName += str(hostsDict[hostName]['num'])
    else:
        hostsDict[hostName] = {}
        hostsDict[hostName]['num'] = 1

    return hostName

if query_yes_no('Do you need a backup of your pre-modified config file?') :
    makeBackup = True
else:
    makeBackup = False

hostsDict = dict()

# config fileのパス
configFilePath = os.environ['HOME'] + '/.ssh/config'

# コマンド実行
subprocess.call('ec2ssh update', shell=True)

baseContent = read_content(configFilePath)

# バックアップ保存
if DEBUG == False and makeBackup == True:
    save_content(configFilePath + '.bak.' + datetime.now().strftime('%Y%m%d_%H%M%S'), baseContent)

pattern = r"Host .*"
renamedContent = re.sub(pattern, renameHostName, baseContent)

if DEBUG == False:
    save_content(configFilePath, renamedContent)

print renamedContent
print 'Success! Please check the above result of modifying your config file.'
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1