Sessions and Channels
The symbols documented on this page are intended to be safe. They may throw exceptions but they should never cause memory corruptions or segfaults if used correctly.
This documents the high-level API around SSH sessions and channels, which is almost everything you need to care about to create a SSH client.
LibSSH.AuthMethod — Type
primitive type AuthMethod <: Enum{Int32} 32Enum for the different authentication methods libssh supports:
AuthMethod_UnknownAuthMethod_NoneAuthMethod_PasswordAuthMethod_PublicKeyAuthMethod_HostBasedAuthMethod_InteractiveAuthMethod_GSSAPI_MIC
LibSSH.AuthStatus — Type
primitive type AuthStatus <: Enum{Int32} 32Enum for the possible authentication responses from a server:
AuthStatus_ErrorAuthStatus_DeniedAuthStatus_PartialAuthStatus_SuccessAuthStatus_InfoAuthStatus_Again
LibSSH.lib.LibSSHException — Type
struct LibSSHException <: ExceptionA custom exception type to represent errors from libssh's C API.
LibSSH.KnownHosts — Type
primitive type KnownHosts <: Enum{Int32} 32Enum for the result of checking a servers public key in the users known hosts file. See is_known_server().
KnownHosts_OkKnownHosts_ChangedKnownHosts_OtherKnownHosts_UnknownKnownHosts_NotFoundKnownHosts_Error
LibSSH.HostVerificationException — Type
struct HostVerificationException <: Exceptionmsg::Stringstatus::LibSSH.KnownHosts
Represents a failed host verification. See the status field for the exact reason.
Sessions
An SSH session represents a connection between a client and a remote server. A session must be authenticated before being able to do anything with it.
Also see the upstream tutorial.
LibSSH.Session — Type
mutable struct SessionRepresents an SSH session. Note that some properties such as the host and port are implemented in getproperty()/setproperty!() by using the internal values of the ssh_session, i.e. they aren't simply fields of the struct. A Session may be owning or non-owning of its internal pointer to a lib.ssh_session.
Session's must be closed explicitly with Base.close(::Session). There is no finalizer, so failing to close a Session will leak resources.
LibSSH.Session — Method
Session(
host::Union{AbstractString, Sockets.IPAddr};
...
) -> LibSSH.Session
Session(
host::Union{AbstractString, Sockets.IPAddr},
port;
socket,
user,
log_verbosity,
auto_connect,
process_config,
pin_tid
) -> LibSSH.Session
Constructor for creating a client session. Use this if you want to connect to a server.
By default libssh will try to follow the settings in any found SSH config files. If a proxyjump is configured for host libssh will try to set up the proxy itself, which usually does not play well with Julia's event loop. In such situations you will probably want to pass process_config=false and set up the proxyjump explicitly using a Forwarder.
Throws
LibSSHException: if a session couldn't be created, or there was an error initializing theuserproperty.
Arguments
host: The host to connect to.port=22: The port to connect to.socket=nothing: Can be an openTCPSocketorRawFDto connect to directly. If this is notnothingit will be used instead ofport. You will need to close the socket afterwards, theSessionwill not do it for you.user=nothing: Set the user to connect as. If unset the current username will be used.log_verbosity=nothing: Set the log verbosity for the session. You can still set the logging level explicitly withsession.log_verbosityif necessary.auto_connect=true: Whether to automatically callconnect().process_config=true: Whether to process any found SSH config files.pin_tid=nothing: An optional thread ID to pin the internal polling tasks to. Polling in a thread-safe way requires a lot of scheduler wakeups, and Julia versions <1.14 are quite inefficient at that with many threads (see #61826). Should only be necessary if you're running Julia with many threads and you observe high CPU usage coming from LibSSH.
Examples
julia> import LibSSH as ssh
julia> session = ssh.Session("foo.org")
julia> session = ssh.Session(ip"12.34.56.78", 2222)LibSSH.Session — Method
Session(
ptr::Ptr{LibSSH.lib.ssh_session_struct};
log_verbosity,
own,
pin_tid
) -> LibSSH.Session
This is only useful if you already have a ssh_session (i.e. in a server). Do not use it if you want a client, use the host/port constructor.
Arguments
ptr: A pointer to thelib.ssh_sessionto wrap.log_verbosity=nothing: argument will be ignored ifownisfalseto avoid accidentally changing the logging level in callbacks when non-owning Sessions are created.own=true: Whether to take ownership ofptr.pin_tid=nothing: See the host/port constructor docstring.
LibSSH.Session — Method
Session(f::Function, args...; kwargs...) -> Any
Do-constructor for Session. All arguments are forwarded to the other constructors.
LibSSH.connect — Function
connect(session::LibSSH.Session)
This will throw an exception if connecting fails. You shouldn't need this unless you've created a session with Session(; auto_connect=false).
Wrapper around lib.ssh_connect().
LibSSH.disconnect — Function
disconnect(session::LibSSH.Session) -> Any
Wrapper around lib.ssh_disconnect().
LibSSH.isconnected — Function
isconnected(session::LibSSH.Session) -> Any
Wrapper around lib.ssh_is_connected().
LibSSH.is_known_server — Function
is_known_server(
session::LibSSH.Session;
throw
) -> LibSSH.KnownHosts
Check if the connected servers public key exists in the SSH known hosts file.
Throws
ArgumentError: If the session isn't connected.HostVerificationException: If verification failed andthrowistrue.
Arguments
throw=true: Whether to throw aHostVerificationExceptionif the verification fails, otherwise the function will just return the verification status.
Wrapper around lib.ssh_session_is_known_server().
LibSSH.get_server_publickey — Function
get_server_publickey(session::LibSSH.Session) -> Any
Get the public key from server of a connected session.
Throws
ArgumentError: If the session isn't connected.LibSSHException: If there was an internal error.
Wrapper around lib.ssh_get_server_publickey().
LibSSH.update_known_hosts — Function
update_known_hosts(session::LibSSH.Session) -> Any
Update the users known hosts file with the sessions server key.
Throws
ArgumentError: If the session isn't connected.LibSSHException: If there was an internal error.
Wrapper around lib.ssh_session_update_known_hosts().
LibSSH.authenticate — Function
authenticate(
session::LibSSH.Session;
password,
privkey,
kbdint_answers,
throw
) -> Union{LibSSH.AuthMethod, LibSSH.AuthStatus, LibSSH.KnownHosts}
This is a helper function that boldly attempts to handle the entire authentication flow by figuring out which authentication methods are still available and calling the appropriate functions for you. It may need to be called multiple times to complete authentication, the idea is that it will only return when user input is needed (e.g. for a password, or to accept a host key, etc).
It can return any of:
- A
KnownHoststo indicate that host verification failed in some way. It will not returnKnownHosts_Ok. - A
AuthStatusto indicate that authentication finished in some way. The caller doesn't need to do anything else in this case but may retry authenticating. It will not returnAuthStatus_Info/AuthStatus_Again/AuthStatus_Partial. - A
AuthMethodto indicate the next method to try. This is only returned for auth methods that require user input (i.e.AuthMethod_PasswordorAuthMethod_Interactive), and the caller must pass the user input next time they callauthenticate().
If you're using this function do not call any of the other userauth_* functions, except for userauth_kbdint_getprompts() to get the server prompts if necessary. authenticate() maintains some internal state to keep track of where it is in authentication, which can be messed up by calling other auth methods yourself.
authenticate() is quite experimental, we suggest testing it with authenticate_cli() to verify it works on the servers you're authenticating to.
Arguments
session: TheSessionto authenticate.password=nothing: A password to authenticate with. Pass this ifauthenticate()previously returnedAuthMethod_Password.privkey=nothing: ASshKeyto authenticate with. Pass this ifauthenticate()previously returnedAuthMethod_PublicKey.kbdint_answers=nothing: Answers to keyboard-interactive prompts from the server. Useuserauth_kbdint_getprompts()to get the prompts ifauthenticate()returnsAuthMethod_Interactiveand then pass the answers in the next call.throw=true: Whether to throw if there's an internal error while authenticating (AuthStatus_Error).
Throws
ArgumentError: If the session isn't connected, or if bothpasswordandkbdint_answersare passed.ErrorException: If there are no more supported authentication methods available.LibSSHException: If there's an internal error andthrow=true.
LibSSH.authenticate_cli — Function
authenticate_cli(
session::LibSSH.Session
) -> Union{LibSSH.AuthStatus, LibSSH.KnownHosts}
Meant to mimic authenticating with the ssh command by calling authenticate() in a loop while prompting the user if necessary. It's useful to use this at the REPL to test whether the server can be authenticated to at all.
Examples
julia> session = ssh.Session("test.com"; user="myuser")
LibSSH.Session(host=test.com, port=22, user=myuser, connected=true)
julia> ssh.authenticate_cli(session)
Password:
[ Info: AuthStatus_Info
One-time password:
[ Info: AuthStatus_Success
AuthStatus_Success::AuthStatus = 0LibSSH.userauth_list — Function
userauth_list(
session::LibSSH.Session;
call_auth_none
) -> Vector{LibSSH.AuthMethod}
Get a list of support authentication methods from the server. This will automatically call userauth_none() beforehand if call_auth_none=true (the default).
Throws
ArgumentError: If the session isn't connected.
Wrapper around lib.ssh_userauth_list().
LibSSH.userauth_none — Function
userauth_none(
session::LibSSH.Session;
throw
) -> LibSSH.AuthStatus
Attempt to authenticate to the server without any credentials. This authentication method is always disabled in practice, but it's still useful to check which authentication methods the server supports (see userauth_list()).
Arguments
session: The session to authenticate.throw=true: Whether to throw if there's an internal error while authenticating (AuthStatus_Error).
Throws
ArgumentError: If the session isn't connected.LibSSHException: If there was an internal error, unlessthrow=false.
Wrapper around lib.ssh_userauth_none().
LibSSH.userauth_password — Function
userauth_password(
session::LibSSH.Session,
password::String;
throw
) -> LibSSH.AuthStatus
Authenticate by username and password. The username will be taken from session.user.
Arguments
session: The session to authenticate.password: The password to authenticate with.throw=true: Whether to throw if there's an internal error while authenticating (AuthStatus_Error).
Throws
ArgumentError: If the session isn't connected.LibSSHException: If there was an internal error, unlessthrow=false.
Wrapper around lib.ssh_userauth_password().
LibSSH.userauth_publickey — Function
userauth_publickey(
session::LibSSH.Session,
path::AbstractString;
passphrase,
throw
) -> LibSSH.AuthStatus
Authenticate by username and private key. The username will be taken from session.user.
Arguments
session: The session to authenticate.path: The private key file path to authenticate with.passphrase=nothing: An optional passphrase for the private key, if it's encrypted.throw=true: Whether to throw if there's an internal error while authenticating (AuthStatus_Error).
Throws
ArgumentError: If the session isn't connected.LibSSHException: If there was an internal error, unlessthrow=false.
Wrapper around lib.ssh_userauth_publickey().
userauth_publickey(
session::LibSSH.Session,
privkey::LibSSH.PKI.SshKey;
throw
) -> LibSSH.AuthStatus
Authenticate by username and private key. The username will be taken from session.user.
Arguments
session: The session to authenticate.privkey: The private key to authenticate with, as aSshKeyobject.throw=true: Whether to throw if there's an internal error while authenticating (AuthStatus_Error).
Throws
ArgumentError: If the session isn't connected.LibSSHException: If there was an internal error, unlessthrow=false.
Wrapper around lib.ssh_userauth_publickey().
LibSSH.userauth_kbdint — Function
userauth_kbdint(
session::LibSSH.Session;
throw
) -> LibSSH.AuthStatus
Attempt to authenticate with the keyboard-interactive method.
Arguments
session: The session to authenticate.throw=true: Whether to throw if there's an internal error while authenticating (AuthStatus_Error).
Throws
ArgumentError: If the session isn't connected.LibSSHException: If there was an internal error, unlessthrow=false.
Wrapper around lib.ssh_userauth_kbdint.
LibSSH.userauth_kbdint_getprompts — Function
userauth_kbdint_getprompts(session::LibSSH.Session) -> Any
Returns all the keyboard-interactive prompts from the server. You should have already called userauth_kbdint(). The KbdintPrompt objects it returns have .msg and .display fields that hold the prompt message and whether to echo the user input (e.g. it will be false for a password and other sensitive input).
This is a combination of lib.ssh_userauth_kbdint_getnprompts() and lib.ssh_userauth_kbdint_getprompt(). It should be preferred over the lower-level functions.
Throws
ArgumentError: If the session isn't connected.
LibSSH.userauth_kbdint_setanswers — Function
userauth_kbdint_setanswers(
session::LibSSH.Session,
answers::Vector{String}
) -> Any
Sets answers for a keyboard-interactive auth session. Uses lib.ssh_userauth_kbdint_setanswer internally.
Arguments
session: The session to authenticate.answers: A vector of answers for each prompt sent by the server.
Throws
ArgumentError: If the session isn't connected, or if the wrong number of answers were passed.LibSSHException: If setting the answers failed.
LibSSH.userauth_gssapi — Function
userauth_gssapi(
session::LibSSH.Session;
throw
) -> LibSSH.AuthStatus
Authenticate with GSSAPI. This is not available on all platforms (see Gssapi.isavailable()).
Arguments
session: The session to authenticate.throw=true: Whether to throw if there's an internal error while authenticating (AuthStatus_Error).
Throws
ArgumentError: If the session isn't connected.ErrorException: If GSSAPI support isn't available.LibSSHException: If there was an internal error, unlessthrow=false.
Wrapper around lib.ssh_userauth_gssapi().
LibSSH.get_error — Method
get_error(session::LibSSH.Session) -> Any
Get the last error set by libssh.
Throws
ArgumentError: If the session has been closed.
Wrapper around lib.ssh_get_error().
Base.isopen — Method
isopen(session::LibSSH.Session) -> Bool
Check if a session is open.
Base.close — Method
close(session::LibSSH.Session)
Closes a session, which will be unusable afterwards. It's safe to call this multiple times.
Throws
ArgumentError: If the session is non-owning. This is not allowed to prevent accidental double-frees.
Channels
SSH channels are things you can create on top of a session to actually do things (like running commands, etc). You can have as many channels on a single session as you like. Channels have certain types, like an exec channel for running commands, and can only be used to do one thing. e.g. if you want to run two commands you must create two channels.
The upstream tutorial has more information about channels.
LibSSH.SshChannel — Type
mutable struct SshChannelptr::Union{Nothing, Ptr{LibSSH.lib.ssh_channel_struct}}owning::Boolsession::Union{Nothing, LibSSH.Session}close_lock::ReentrantLocklocal_eof::Boolcallbacks::Union{Nothing, LibSSH.ChannelCallbacks}_pending_close::Bool_poll_seen_open::Bool_poll_done::Channel{Union{Nothing, Int64}}
Wraps a lib.ssh_channel. An SshChannel can be owning or non-owning of a pointer to the underlying lib.ssh_channel, and only owning SshChannels can be closed with close(::SshChannel).
The type is named SshChannel to avoid confusion with Julia's own Channel type.
SshChannel's must be closed explicitly with Base.close(::SshChannel). There is no finalizer, so failing to close an SshChannel will leak resources.
LibSSH.SshChannel — Method
SshChannel(session::LibSSH.Session) -> Any
Create a channel from an existing session. Note that creating the channel will fail unless the session is connected and authenticated.
LibSSH.SshChannel — Method
SshChannel(f::Function, session::LibSSH.Session) -> Any
Do-constructor for a SshChannel. This will ensure that the channel is closed after f() completes.
Example:
data = ssh.SshChannel(session) do sshchan
return 42
end
@assert data == 42LibSSH.SshChannel — Method
SshChannel(ptr::Ptr{LibSSH.lib.ssh_channel_struct}; ...)
SshChannel(
ptr::Ptr{LibSSH.lib.ssh_channel_struct},
session;
own
) -> LibSSH.SshChannel
Wrap a SshChannel around an already existing lib.ssh_channel. Don't use this unless you know what you're doing, prefer the SshChannel(::Session) constructor instead.
LibSSH.ChannelCallbacks — Type
mutable struct ChannelCallbacksWrapper around lib.ssh_channel_callbacks_struct.
LibSSH.ChannelCallbacks — Method
ChannelCallbacks(; ...) -> LibSSH.ChannelCallbacks
ChannelCallbacks(
userdata;
on_data,
on_eof,
on_close,
on_signal,
on_exit_status,
on_exit_signal,
on_pty_request,
on_shell_request,
on_auth_agent_req,
on_x11_req,
on_pty_window_change,
on_exec_request,
on_env_request,
on_subsystem_request,
on_write_wontblock,
on_open_response,
on_request_response
) -> LibSSH.ChannelCallbacks
Create a callbacks object to set on a channel. A default function is registered for each callback and it will print a warning if a callback was requested but not found, so you don't need to set all of the callbacks for the channel to work properly. The only exceptions are:
on_write_wontblock=Returns(0)on_open_response=Returns(nothing)on_request_response=Returns(nothing)
Which have default callbacks because they're always called but rarely necessary to set explicitly.
The callback functions should all match the signature f(::Session, ::SshChannel, args..., userdata). Note that some argument types will automatically be converted from the C types:
lib.ssh_session-> a non-owningSessionlib.ssh_channel-> a non-owningSshChannelCstring->StringCint/Cuint/Cchar->Int/UInt/Char
The userdata pointer in the C callback signatures will automatically be converted to its original Julia type. Boolean argments are not yet converted from their Cint types to Bool.
Do not use Session or SshChannel arguments outside the callback functions. They are temporary non-owning wrappers, and they will be unusable after the callback has been executed.
Arguments
All of these are also properties that can be set after creation.
userdata: An arbitrary object that will be passed to each callback function.on_data:f(::Session, ::SshChannel, ::Vector{UInt8}, Int, userdata)::Inton_eof:f(::Session, ::SshChannel, userdata)::Nothingon_close:f(::Session, ::SshChannel, userdata)::Nothingon_signal:f(::Session, ::SshChannel, ::String, userdata)::Nothingon_exit_status:f(::Session, ::SshChannel, ::Int, userdata)::Nothingon_exit_signal:f(::Session, ::SshChannel, ::String, ::Int, ::String, ::String, userdata)::Nothingon_pty_request:f(::Session, ::SshChannel, ::String, ::Int, ::Int, ::Int, ::Int, userdata)::Boolon_shell_request:f(::Session, ::SshChannel, userdata)::Boolon_auth_agent_req:f(::Session, ::SshChannel, userdata)::Nothingon_x11_req:f(::Session, ::SshChannel, ::Int, ::String, ::String, ::UInt, userdata)::Nothingon_pty_window_change:f(::Session, ::SshChannel, ::Int, ::Int, ::Int, ::Int, userdata)::Boolon_exec_request:f(::Session, ::SshChannel, ::String, userdata)::Boolon_env_request:f(::Session, ::SshChannel, ::String, ::String, userdata)::Boolon_subsystem_request:f(::Session, ::SshChannel, ::String, userdata)::Boolon_write_wontblock:f(::Session, ::SshChannel, ::UInt, userdata)::Inton_open_response:f(::Session, ::SshChannel, ::Bool, userdata)::Nothingon_request_response:f(::Session, ::SshChannel, userdata)::Nothing
LibSSH.set_channel_callbacks — Function
set_channel_callbacks(
sshchan::LibSSH.SshChannel,
callbacks::LibSSH.ChannelCallbacks
)
Wrapper around lib.ssh_set_channel_callbacks() and lib.ssh_remove_channel_callbacks(). Unlike lib.ssh_set_channel_callbacks() this will replace any existing callbacks.
Throws
LibSSHException: If setting the callbacks failed.
LibSSH.channel_request_send_exit_status — Function
channel_request_send_exit_status(
sshchan::LibSSH.SshChannel,
status::Integer
)
Sends an exit status in reponse to an exec request. Wrapper around lib.ssh_channel_request_send_exit_status().
Base.wait — Method
wait(
sshchan::LibSSH.SshChannel;
throw
) -> Union{Nothing, Int64}
Wait until an owning channel finishes (its remote end sends EOF, an error occurs, or it is closed). Returns nothing if the channel/session was closed before EOF, otherwise the terminating lib.ssh_channel_poll() result.
Throws
LibSSHException: IfSSH_ERRORis returned andthrow=true.
Arguments
sshchan: TheSshChannelto wait on.throw=true: Whether to throw an exception ifSSH_ERRORis returned.
Base.isassigned — Method
isassigned(sshchan::LibSSH.SshChannel) -> Bool
Check if the channel holds a valid pointer to a lib.ssh_channel.
Base.isopen — Method
isopen(sshchan::LibSSH.SshChannel) -> Any
Checks if the channel is open. Wrapper around lib.ssh_channel_is_open().
Base.close — Method
close(sshchan::LibSSH.SshChannel; allow_fail)
Closes the channel, and then frees its memory. To avoid the risk of double-frees, this function may only be called on owning SshChannels. It will hold the close_lock of the channel during execution.
Arguments
sshchan: TheSshChannelto close.allow_fail=false: Whether to throw an exception if the call tolib.ssh_channel_close()fails. In some cases it can fail for valid reasons, such as the socket already having been closed by the other end (this will result in aSocket error: disconnectederror).
Base.eof — Method
eof(sshchan::LibSSH.SshChannel) -> Any
Check if an EOF has been sent by the remote end. This does not imply that an EOF has been sent from the local end and thus the channel is not writable (for that, use iswritable(::SshChannel)). Check SshChannel.local_eof to check if an EOF has been sent from the local end.
Wrapper around lib.ssh_channel_is_eof().
Base.closewrite — Method
closewrite(
sshchan::LibSSH.SshChannel;
allow_fail
) -> Union{Nothing, Bool}
Sends an EOF message. Calling this function will trigger any waiting callbacks.
Throws
ArgumentError: if the channel is not writable.
Wrapper around lib.ssh_channel_send_eof().
Arguments
sshchan: TheSshChannelto send an EOF on.allow_fail=false: Whether to throw an exception if the call tolib.ssh_channel_send_eof()fails. In some cases it can fail for valid reasons, such as the socket already having been closed by the other end (this will result in aSocket error: disconnectederror).
Base.iswritable — Method
iswritable(sshchan::LibSSH.SshChannel) -> Bool
Check if the channel is writable.
Base.write — Method
write(
sshchan::LibSSH.SshChannel,
data::AbstractString;
stderr
) -> Any
Write a string to the channel and return the number of code units written.
Wrapper around lib.ssh_channel_write()/lib.ssh_channel_write_stderr().
Base.write — Method
write(
sshchan::LibSSH.SshChannel,
data::Vector{UInt8};
stderr
) -> Any
Write a byte array to the channel and return the number of bytes written (should always match the length of the array, unless there was an error, in which case this will throw an exception).
Wrapper around lib.ssh_channel_write()/lib.ssh_channel_write_stderr().
Channel operations
You should prefer using these instead of more low-level methods, if you can.
Command execution
LibSSH.jl attempts to mimic Julia's API for running local commands with run() etc. But some features are not supported and we attempt to document all of the differences.
LibSSH.SshProcessFailedException — Type
struct SshProcessFailedException <: Exceptionprocess::LibSSH.SshProcess
This is analogous to ProcessFailedException.
LibSSH.SshProcess — Type
mutable struct SshProcessout::Vector{UInt8}err::Vector{UInt8}cmd::Union{Nothing, Cmd, String}exitcode::Int64_sshchan::Union{Nothing, LibSSH.SshChannel}_task::Union{Nothing, Task}_verbose::Bool
This is analogous to Base.Process, it represents a command running over an SSH session. The stdout and stderr output are stored as byte arrays in SshProcess.out and SshProcess.err respectively. They can be converted to strings using e.g. String(copy(process.out)).
Base.success — Method
success(process::LibSSH.SshProcess) -> Bool
Check if the process succeeded.
Base.run — Method
run(
cmd::Union{Cmd, String},
session::LibSSH.Session;
wait,
verbose,
combine_outputs,
print_out
) -> LibSSH.SshProcess
Run a command on the remote host over an SSH session. Things that aren't supported compared to run():
- Pipelined commands (use a regular pipe like
foo | barinstead). - Setting the directory to execute the command in.
An easy way of getting around these restrictions is to pass the command as a String instead of Cmd.
Throws
SshProcessFailedException: if the command fails andignorestatus()wasn't used.LibSSHException: if running the command fails for some other reason.
Arguments
cmd: The command to run. This will be converted to a string for running remotely.session: The session to run the command over.wait=true: Wait for the command to finish before returning.verbose=false: Print debug logging messages. Note that this is not the same as setting thelog_verbosityon aSession.combine_outputs=true: Write thestderrcommand output to theIOBufferfor the commandsstdout. If this istruethenSshProcess.outandSshProcess.errwill refer to the same object.print_out=true: Print the output (stdout + stderr by default) of the command.
Examples
julia> import LibSSH as ssh
julia> ssh.DemoServer(2222; password="foo") do
session = ssh.Session("127.0.0.1", 2222)
@assert ssh.userauth_password(session, "foo") == ssh.AuthStatus_Success
@info "1"
run(`echo foo`, session)
println()
@info "2"
run(ignorestatus(`foo`), session)
println()
@info "3"
# Pass a string to avoid hacking around Cmd syntax
run("cd /tmp && pwd", session)
end
[ Info: 1
foo
[ Info: 2
sh: line 1: foo: command not found
[ Info: 3
/tmpBase.read — Method
read(
cmd::Union{Cmd, String},
session::LibSSH.Session,
_::Type{String}
) -> String
Read the output from the command as a String.
Examples
julia> import LibSSH as ssh
julia> ssh.DemoServer(2222; password="foo") do
session = ssh.Session("127.0.0.1", 2222)
@assert ssh.userauth_password(session, "foo") == ssh.AuthStatus_Success
@show read(`echo foo`, session, String)
end
read(`echo foo`, session, String) = "foo\n"Base.readchomp — Method
readchomp(
cmd::Union{Cmd, String},
session::LibSSH.Session
) -> SubString{String}
readchomp() for remote commands.
Base.success — Method
success(
cmd::Union{Cmd, String},
session::LibSSH.Session
) -> Bool
Check the command succeeded.
Direct port forwarding
LibSSH.Forwarder — Type
mutable struct Forwarderremotehost::Stringremoteport::Int64localinterface::Sockets.IPAddrlocalport::Int64out::Union{Nothing, Sockets.TCPSocket}_listen_server::Sockets.TCPServer_listener_task::Union{Nothing, Task}_clients::Vector{LibSSH._ForwardingClient}_next_client_id::Int64_session::LibSSH.Sessionverbose::Bool
This object manages a direct forwarding channel between localport and remotehost:remoteport. Fields beginning with an underscore _ are private and should not be used.
Forwarder's must be closed explicitly with Base.close(::Forwarder). There is no finalizer, so failing to close a Forwarder will leak resources.
LibSSH.Forwarder — Method
Forwarder(
session::LibSSH.Session,
localport::Int64,
remotehost::String,
remoteport::Int64;
verbose,
localinterface
) -> LibSSH.Forwarder
Create a Forwarder object to forward data from localport to remotehost:remoteport. This will handle an internal SshChannel for forwarding.
Arguments
session: The session to create a forwarding channel over.localport: The local port to bind to.remotehost: The remote host.remoteport: The remote port to bind to.verbose: Print logging messages on callbacks etc (not equivalent to settinglog_verbosityon aSession).localinterface=IPv4(0): The interface to bindlocalporton.
LibSSH.Forwarder — Method
Forwarder(
session::LibSSH.Session,
remotehost::String,
remoteport::Int64;
verbose
) -> LibSSH.Forwarder
Create a Forwarder object that will forward its data to a single TCPSocket. This is useful if there is only one client and binding to a port available to other processes is not desirable. The socket will be stored in the Forwarder.out property, and it will be closed when the Forwarder is closed.
All arguments mean the same as in Forwarder(::Session, ::Int, ::String, ::Int).
LibSSH.Forwarder — Method
Forwarder(f::Function, args...; kwargs...) -> Any
Do-constructor for a Forwarder. All arguments are forwarded to the other constructors.
Base.close — Method
close(forwarder::LibSSH.Forwarder)
Close a Forwarder. This will close all client channels and the listening local socket.