Python remote ssh using public key

Quite often we come across scenarios where putting passwords in config or code is not allowed. In such situations, we can still do remote ssh using netmiko module combined with public key based authentication. Here is the sample code:

from netmiko import ConnectHandler

RemoteHost = "192.168.1.3"
username = "someuser"
keyfile = "/home/someuser/.ssh/id_rsa.pub"

hostObj = {
    'device_type': 'linux',
    'host': RemoteHost,
    'username': username,
    'use_keys': True,
    'key_file': keyfile,
}

try:
  net_connect = ConnectHandler(**hostObj)
  sshstatus = 0

except:
  LogMessage = "ssh failed on {}".format(RemoteHost)
  print(LogMessage)

if sshstatus == 0:
  ListFileCmd = "ls -tr /tmp | tail -1"
  res = net_connect.send_command(ListFileCmd)
  print(res)