Created
May 22, 2011 15:02
-
-
Save guyromm/985548 to your computer and use it in GitHub Desktop.
set up a public key remotely & write an .ssh/config entry for a clean linux machine install
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
import sys,pexpect,json,os,re | |
from commands import getstatusoutput as gso | |
def writekey(host,user,pss,key): | |
ssh_newkey = 'Are you sure you want to continue connecting' | |
# my ssh command line | |
cmd = 'ssh %s@%s mkdir -p ~/.ssh ; echo "%s" >> ~/.ssh/authorized_keys2'%(user,host,key) | |
#pexpect ssh bit taken from http://linux.byexamples.com/archives/346/python-how-to-access-ssh-with-pexpect/ | |
p=pexpect.spawn(cmd) | |
i=p.expect([ssh_newkey,'password:',pexpect.EOF]) | |
if i==0: | |
print "I say yes" | |
p.sendline('yes') | |
i=p.expect([ssh_newkey,'password:',pexpect.EOF]) | |
if i==1: | |
print "I give password", | |
p.sendline(pss) | |
p.expect(pexpect.EOF) | |
elif i==2: | |
print "I either got key or connection timeout" | |
pass | |
print p.before # print out the result | |
return i | |
argv = sys.argv[1] | |
print argv | |
a = json.loads(argv) | |
st,iam = gso('whoami') | |
assert st==0; iam = iam.strip() | |
k = open(os.path.join('/home',iam,'.ssh/authorized_keys2'),'r').read().split('\n')[0].strip() | |
pat = """ | |
Host %s | |
HostName %s | |
User %s | |
ForwardAgent yes | |
IdentityFile ~/.ssh/id_rsa | |
"""%(a['name'],a['host'],a['user']) | |
#print pat | |
wk = writekey(a['host'],a['user'],a['password'],k) | |
print 'wk = %s'%wk | |
if wk in [1,2]: | |
print 'writing .ssh/config' | |
fn = os.path.join('/home',iam,'.ssh','config') | |
cc = open(fn,'r').read() | |
if re.compile(re.escape('Host %s'%a['name'])).search(cc): raise Exception('already have %s in .ssh/config'%a['name']) | |
cc+='\n'+pat | |
fp = open(fn,'w') ; fp.write(cc) ; fp.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment