This repository has been archived by the owner on Jan 22, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtransmit-to-sshconfig.py
executable file
·146 lines (117 loc) · 4.14 KB
/
transmit-to-sshconfig.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import io
import os
import sys
import xml.etree.ElementTree as ET
import unicodedata,re
def slugify(str):
slug = unicodedata.normalize("NFKD",unicode(str)).encode("ascii", "ignore")
slug = re.sub("\(", "[", slug)
slug = re.sub("\)", "]", slug)
slug = re.sub(r"/[^\w]+", " ", slug)
slug = "-".join(slug.lower().strip().split())
return slug
def query_yes_no(question, default="yes"):
"""Ask a yes/no question via raw_input() and return their answer.
"question" is a string that is presented to the user.
"default" is the presumed answer if the user just hits <Enter>.
It must be "yes" (the default), "no" or None (meaning
an answer is required of the user).
The "answer" return value is True for "yes" or False for "no".
"""
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")
BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)
#following from Python cookbook, #475186
def has_colours(stream):
if not hasattr(stream, "isatty"):
return False
if not stream.isatty():
return False # auto color only on TTYs
try:
import curses
curses.setupterm()
return curses.tigetnum("colors") > 2
except:
# guess false in case of error
return False
has_colours = has_colours(sys.stdout)
def printout(text, colour=WHITE):
if has_colours:
seq = "\x1b[1;%dm" % (30+colour) + text + "\x1b[0m"
sys.stdout.write(seq)
else:
sys.stdout.write(text)
user_dir = os.path.expanduser('~')
favorites_file = ET.parse(user_dir + '/Library/Application Support/Transmit/Favorites/Favorites.xml')
favorites = favorites_file.findall('./object[@type="FAVORITE"]')
sshconfig_file = user_dir + '/.ssh/config';
if query_yes_no("This script will add all your Transmit SFTP favorites to your SSH config file located in %s, do you want to continue?" % sshconfig_file) is False:
printout("[info] ", GREEN)
print "Import aborted, no Transmit favorites have been added"
sys.exit(0)
sshconfig = open(sshconfig_file, 'a+')
for i, favorite in enumerate(favorites):
attributes = favorite.findall('./attribute[@name="protocol"]')
has_sftp = False
for attribute in attributes:
if attribute.text == 'SFTP':
has_sftp = True
continue
if has_sftp is False:
continue
collection_id = favorite.find('./relationship[@name="collection"]').get('idrefs')
collection = favorites_file.find("./object[@id='%s']" % collection_id)
# Skip history
if collection.get('type') == 'HISTORYCOLLECTION':
continue;
collection_name = collection.find("attribute[@name='name']").text
host = slugify(collection_name.lower() + '/' + favorite.find('./attribute[@name="nickname"]').text)
hostname = favorite.find('./attribute[@name="server"]').text
port = int(favorite.find('./attribute[@name="port"]').text)
user = favorite.find('./attribute[@name="username"]').text
item = [
"Host %s" % host,
"\tHostName %s" % hostname,
"\tPort %s" % port,
"\tUser %s" % user,
"\n"
]
# Remove port if not set
if port <= 0 :
item.pop(2)
if i == 1:
sshconfig.write('\n')
# Skip if item is already in file
item_line = '\n'.join(item).encode('utf8')
sshconfig.seek(0)
if item_line in sshconfig.read():
printout("[info] ", YELLOW)
print "Skipped %s: already found in file" % host
continue
# Write item to file
sshconfig.write(item_line)
printout("[info] ", GREEN)
print "Added %s" % host
sshconfig.close()
printout("[info] ", GREEN)
print "All SFTP favorites from Transmit have been added to %s" % sshconfig_file