Skip to content

Instantly share code, notes, and snippets.

@tmtk75
Last active December 13, 2015 22:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tmtk75/4982391 to your computer and use it in GitHub Desktop.
Save tmtk75/4982391 to your computer and use it in GitHub Desktop.
#!/usr/bin/env expect
set user "your_username"
set prompt ".*$user.*"
set domain "subdomain.yourdomain.com"
set timeout 60
if { $argc < 2 } {
puts "usage: $argv0 <public-key-absolute-path> <ssh-password>
Append a public key to ~/.ssh/authorized_keys of $user@$domain
ex) $ ./append-publickey.exp /home/foobar/.ssh/id_rsa.pub abc123
"
exit 1
}
set pubkey_path [lindex $argv 0]
set password [lindex $argv 1]
### Copy a public key to a domain at $HOME
spawn scp $pubkey_path $user@$domain:./
sleep 1
expect "password: "
send "$password\r"
expect -re $prompt
### Log in with password and append the public key to authorized_keys
spawn ssh $user@$domain
sleep 1
expect "password: "
send "$password\r"
expect -re $prompt
set pubkey_name [file tail $pubkey_path]
send "cat ~/$pubkey_name >> ~/.ssh/authorized_keys\r"
send "chmod 600 ~/.ssh/authorized_keys\r"
send "chmod 700 ~/.ssh\r"
send "rm ~/$pubkey_name\r"
expect -re $prompt
### Exit the session
send "exit\r"
expect eof
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment