Skip to content

Instantly share code, notes, and snippets.

@stiakov
Last active September 6, 2019 17:59
Show Gist options
  • Select an option

  • Save stiakov/7c06480321adec26a3a1d1e7df428320 to your computer and use it in GitHub Desktop.

Select an option

Save stiakov/7c06480321adec26a3a1d1e7df428320 to your computer and use it in GitHub Desktop.
Automatize ssh logins

Automatize your remote logins through ssh

Requirements

You need expect scripting language to run this task.

  • In debian based distros run: $ sudo apt install expect

  • In MacOS: $ brew install expect

Setup

  1. Create a file that will store your expect script:

$ touch ~/my_connection.exp

  1. Edit your file in your favorite editor:
#!/usr/bin/expect

set timeout 5

set ip [lindex $argv 0]

set user [lindex $argv 1]

set password [lindex $argv 2]

spawn ssh "$user\@$ip"

expect "Password:"

send "$password\r";

interact
  1. Modifiy permissions to your expect script:

$ chmod +x ~/my_connection.exp

  1. Run your script using arguments like this, use your own args:

$ ~/my_connection.exp 192.198.0.100 root p455w0rd

Customizing (Optional)

Hide your pass

Avoid to expose your password exporting it from your .zshrc / .bashrc.

According to your $SHELL, use the proper file, in my case I'm using ZSH so I'll edit my ~/.zshrc.

  1. Export your password as an environment variable:

$ echo "export hid_pass='p455word'"

  1. Update your $Shell after every modification:

$ exec $SHELL or $ source ~/.zshrc

  1. Use your script without exposing your password:

$ ~/my_connection.exp 192.168.0.100 root $hid_pass

Run your connection with a couple keystrokes

Create an alias to run the connection within preset args.

  1. Add your alias to your $SHELL (.zshrc / .bashrc):

$ echo "alias mycon='~/my_connection.exp 192.168.0.100 root $hid_pass'"

  1. Don't forget to update the $SHELL after every modification:

$ exec $SHELL or $ source ~/.zshrc

  1. Call the connection using your alias, and wait until the connection is done:

$ mycon

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment