Sample code for 30+ languages & platforms
Lua

Authenticate an IMAP SSH Tunnel with a Private Key

See more IMAP Examples

Demonstrates the Chilkat Imap.SshAuthenticatePk method, which authenticates the SSH tunnel using a username and an SshKey private key. The first argument is the SSH login name and the second is the private key. Call SshOpenTunnel first; the matching public key must already be authorized for the login on the SSH server.

Note: The private-key path is relative to the application's current working directory. Supply the path to your own key file.

Background: Public-key authentication is the usual choice for unattended/automated SSH access: the private key stays on the client and the server is configured to trust the corresponding public key, so no reusable password travels over the wire. The SshKey object can import keys in several formats — this example uses an OpenSSH private key.

Chilkat Lua Downloads

Lua
local chilkat = require("chilkat")

-- Demonstrates the Imap.SshAuthenticatePk method, which authenticates the SSH tunnel using a
-- username and a private key.  The 1st argument is the SSH login name and the 2nd is an SshKey
-- private key.  Call SshOpenTunnel first.

local imap = chilkat.Imap.new()

local sshPort = 22
local success = imap:ssh_open_tunnel("ssh.example.com", sshPort)
if not success then
    print(imap.last_error_text)
    return
end

-- Load the SSH private key.  LoadText returns the file's text, which is then imported.
local privKey = chilkat.SshKey.new()
local keyStr = privKey:load_text("qa_data/id_rsa")
if not privKey.last_method_success then
    print(privKey.last_error_text)
    return
end

success = privKey:from_open_ssh_private_key(keyStr)
if not success then
    print(privKey.last_error_text)
    return
end

-- Authenticate the SSH tunnel with the private key.  The matching public key must already be
-- authorized for the login on the SSH server.
success = imap:ssh_authenticate_pk("sshUser", privKey)
if not success then
    print(imap.last_error_text)
    return
end

-- With the SSH tunnel in place, connect and log in to the IMAP server as usual.  The IMAP
-- traffic flows through the tunnel automatically.
imap.ssl = true
imap.port = 993
success = imap:connect("imap.example.com")
if not success then
    print(imap.last_error_text)
    return
end

success = imap:login("user@example.com", "myPassword")
if not success then
    print(imap.last_error_text)
    return
end

success = imap:disconnect()
if not success then
    print(imap.last_error_text)
    return
end

success = imap:ssh_close_tunnel()
if not success then
    print(imap.last_error_text)
    return
end