Skip to content

Instantly share code, notes, and snippets.

@andersy005
Forked from graysonchao/paramiko_yubikey.py
Created August 4, 2020 23:15
Show Gist options
  • Save andersy005/05d6eec481199be49eca78fc3069c6dc to your computer and use it in GitHub Desktop.
Save andersy005/05d6eec481199be49eca78fc3069c6dc to your computer and use it in GitHub Desktop.
RSA+YubiKey 2FA example using Paramiko
username = raw_input("Enter SSH username:")
yubikey_string = getpass.getpass('Enter YubiKey OTP:')
client = paramiko.client.SSHClient()
# Any means of getting the PKey will do. This code assumes you've only got one key loaded in your active ssh-agent.
# See also:
# - http://docs.paramiko.org/en/1.17/api/keys.html#paramiko.pkey.PKey
# - http://docs.paramiko.org/en/1.17/api/client.html#paramiko.client.SSHClient.connect
my_pkey = paramiko.agent.Agent().get_keys()[0]
try:
client.connect(
hostname="ssh.example.com",
port=22,
username=username,
look_for_keys=True,
pkey=my_pkey
)
except paramiko.ssh_exception.SSHException:
pass
transport = client.get_transport()
# Sometimes sshd is configured to use 'keyboard-interactive' instead of 'password' to implement the YubiKey challenge.
# In that case, you can use something like this.
# The code below assumes the server will only ask one question and expect the YubiKey OTP as an answer.
# If there's more questions to answer, you should handle those per the docs at:
# http://docs.paramiko.org/en/1.17/api/transport.html#paramiko.transport.Transport.auth_interactive
#
# def yubikey_handler(title, instructions, prompt_list):
# return (yubikey_string)
# transport.auth_interactive(username, yubikey_handler)
transport.auth_password(username, self.yubikey_string)
# You should now be able to use client as the authenticated user.
client.exec_command("whatever")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment