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
— Typeprimitive type AuthMethod <: Enum{Int32} 32
Enum for the different authentication methods libssh supports:
AuthMethod_Unknown
AuthMethod_None
AuthMethod_Password
AuthMethod_PublicKey
AuthMethod_HostBased
AuthMethod_Interactive
AuthMethod_GSSAPI_MIC
LibSSH.AuthStatus
— Typeprimitive type AuthStatus <: Enum{Int32} 32
Enum for the possible authentication responses from a server:
AuthStatus_Error
AuthStatus_Denied
AuthStatus_Partial
AuthStatus_Success
AuthStatus_Info
AuthStatus_Again
LibSSH.lib.LibSSHException
— Typestruct LibSSHException <: Exception
A custom exception type to represent errors from libssh's C API.
LibSSH.KnownHosts
— Typeprimitive type KnownHosts <: Enum{Int32} 32
Enum for the result of checking a servers public key in the users known hosts file. See is_known_server()
.
KnownHosts_Ok
KnownHosts_Changed
KnownHosts_Other
KnownHosts_Unknown
KnownHosts_NotFound
KnownHosts_Error
LibSSH.HostVerificationException
— Typestruct HostVerificationException <: Exception
msg::String
status::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
— Typemutable struct Session
ptr::Union{Nothing, Ptr{LibSSH.lib.ssh_session_struct}}
owning::Bool
closeables::Vector{Any}
server_callbacks::Union{Nothing, LibSSH.Callbacks.ServerCallbacks}
log_verbosity::Int64
ssh_dir::Union{Nothing, String}
gssapi_server_identity::Union{Nothing, String}
process_config::Bool
_lock::ReentrantLock
_auth_methods::Union{Nothing, Vector{LibSSH.AuthMethod}}
_attempted_auth_methods::Vector{LibSSH.AuthMethod}
_require_init_kbdint::Bool
_waiter_request::Base.Event
_wakeup::LibSSH.CloseableCondition
_waiter_stop_flag::Bool
_waiter_task::Task
Represents 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
.
It must be closed explicitly with Base.close(::Session)
or it will leak memory.
LibSSH.Session
— MethodSession(
host::Union{AbstractString, Sockets.IPAddr};
...
) -> LibSSH.Session
Session(
host::Union{AbstractString, Sockets.IPAddr},
port;
socket,
user,
log_verbosity,
auto_connect,
process_config
) -> 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 theuser
property.
Arguments
host
: The host to connect to.port=22
: The port to connect to.socket=nothing
: Can be an openTCPSocket
orRawFD
to connect to directly. If this is notnothing
it will be used instead ofport
. You will need to close the socket afterwards, theSession
will 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.auto_connect=true
: Whether to automatically callconnect()
.process_config=true
: Whether to process any found SSH config files.
Examples
julia> import LibSSH as ssh
julia> session = ssh.Session("foo.org")
julia> session = ssh.Session(ip"12.34.56.78", 2222)
LibSSH.Session
— MethodSession(
ptr::Ptr{LibSSH.lib.ssh_session_struct};
log_verbosity,
own
) -> 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_session
to wrap.log_verbosity=nothing
: Set the log verbosity for the session. This argument will be ignored ifown
isfalse
to avoid accidentally changing the logging level in callbacks when non-owning Sessions are created. You can still set the logging level explicitly withsession.log_verbosity
if necessary.own=true
: Whether to take ownership ofptr
, i.e. whether to register a finalizer to free the memory.
LibSSH.Session
— MethodSession(f::Function, args...; kwargs...) -> Any
Do-constructor for Session
. All arguments are forwarded to the other constructors.
LibSSH.connect
— Functionconnect(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
— Functiondisconnect(session::LibSSH.Session)
Wrapper around lib.ssh_disconnect()
.
This will close all channels created from the session.
LibSSH.isconnected
— Functionisconnected(session::LibSSH.Session) -> Bool
Wrapper around lib.ssh_is_connected()
.
LibSSH.is_known_server
— Functionis_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 andthrow
istrue
.
Arguments
throw=true
: Whether to throw aHostVerificationException
if the verification fails, otherwise the function will just return the verification status.
Wrapper around lib.ssh_session_is_known_server()
.
LibSSH.get_server_publickey
— Functionget_server_publickey(
session::LibSSH.Session
) -> LibSSH.PKI.SshKey
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
— Functionupdate_known_hosts(session::LibSSH.Session)
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
— Functionauthenticate(
session::LibSSH.Session;
password,
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
KnownHosts
to indicate that host verification failed in some way. It will not returnKnownHosts_Ok
. - A
AuthStatus
to 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
AuthMethod
to indicate the next method to try. This is only returned for auth methods that require user input (i.e.AuthMethod_Password
orAuthMethod_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
: TheSession
to authenticate.password=nothing
: A password to authenticate with. Pass this ifauthenticate()
previously returnedAuthMethod_Password
.kbdint_answers=nothing
: Answers to keyboard-interactive prompts from the server. Useuserauth_kbdint_getprompts()
to get the prompts ifauthenticate()
returnsAuthMethod_Interactive
and 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 bothpassword
andkbdint_answers
are passed.ErrorException
: If there are no more supported authentication methods available.LibSSHException
: If there's an internal error andthrow=true
.
LibSSH.authenticate_cli
— Functionauthenticate_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 = 0
LibSSH.userauth_list
— Functionuserauth_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
— Functionuserauth_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
— Functionuserauth_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_kbdint
— Functionuserauth_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
— Functionuserauth_kbdint_getprompts(
session::LibSSH.Session
) -> Vector{LibSSH.KbdintPrompt}
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
— Functionuserauth_kbdint_setanswers(
session::LibSSH.Session,
answers::Vector{String}
)
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
— Functionuserauth_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
— Methodget_error(session::LibSSH.Session) -> String
Get the last error set by libssh.
Throws
ArgumentError
: If the session has been closed.
Wrapper around lib.ssh_get_error()
.
Base.isopen
— Methodisopen(session::LibSSH.Session) -> Bool
Check if a session is open.
Base.close
— Methodclose(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.
Base.wait
— Methodwait(session::LibSSH.Session) -> Any
Waits for data to be readable/writable on a session.
Throws
InvalidStateException
: If the session is already closed, or is closed while waiting.
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
— Typemutable struct SshChannel
ptr::Union{Nothing, Ptr{LibSSH.lib.ssh_channel_struct}}
owning::Bool
session::Union{Nothing, LibSSH.Session}
close_lock::ReentrantLock
local_eof::Bool
callbacks::Union{Nothing, LibSSH.Callbacks.ChannelCallbacks}
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 SshChannel
s can be closed with close(::SshChannel)
.
The type is named SshChannel
to avoid confusion with Julia's own Channel
type.
LibSSH.SshChannel
— MethodSshChannel(session::LibSSH.Session) -> LibSSH.SshChannel
Create a channel from an existing session. Note that creating the channel will fail unless the session is connected and authenticated.
LibSSH.SshChannel
— MethodSshChannel(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 == 42
LibSSH.SshChannel
— MethodSshChannel(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.Callbacks.ChannelCallbacks
— Typemutable struct ChannelCallbacks
Wrapper around lib.ssh_channel_callbacks_struct
.
LibSSH.Callbacks.ChannelCallbacks
— MethodChannelCallbacks(; ...) -> LibSSH.Callbacks.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.Callbacks.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-owningssh.Session
lib.ssh_channel
-> a non-owningssh.SshChannel
Cstring
->String
Cint
/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 ssh.Session
or ssh.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)::Int
on_eof
:f(::Session, ::SshChannel, userdata)::Nothing
on_close
:f(::Session, ::SshChannel, userdata)::Nothing
on_signal
:f(::Session, ::SshChannel, ::String, userdata)::Nothing
on_exit_status
:f(::Session, ::SshChannel, ::Int, userdata)::Nothing
on_exit_signal
:f(::Session, ::SshChannel, ::String, ::Int, ::String, ::String, userdata)::Nothing
on_pty_request
:f(::Session, ::SshChannel, ::String, ::Int, ::Int, ::Int, ::Int, userdata)::Bool
on_shell_request
:f(::Session, ::SshChannel, userdata)::Bool
on_auth_agent_req
:f(::Session, ::SshChannel, userdata)::Nothing
on_x11_req
:f(::Session, ::SshChannel, ::Int, ::String, ::String, ::UInt, userdata)::Nothing
on_pty_window_change
:f(::Session, ::SshChannel, ::Int, ::Int, ::Int, ::Int, userdata)::Bool
on_exec_request
:f(::Session, ::SshChannel, ::String, userdata)::Bool
on_env_request
:f(::Session, ::SshChannel, ::String, ::String, userdata)::Bool
on_subsystem_request
:f(::Session, ::SshChannel, ::String, userdata)::Bool
on_write_wontblock
:f(::Session, ::SshChannel, ::UInt, userdata)::Int
on_open_response
:f(::Session, ::SshChannel, ::Bool, userdata)::Nothing
on_request_response
:f(::Session, ::SshChannel, userdata)::Nothing
LibSSH.set_channel_callbacks
— Functionset_channel_callbacks(
sshchan::LibSSH.SshChannel,
callbacks::LibSSH.Callbacks.ChannelCallbacks
) -> LibSSH.Callbacks.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
— Functionchannel_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()
.
LibSSH.poll_loop
— Functionpoll_loop(
sshchan::LibSSH.SshChannel;
throw
) -> Union{Nothing, Int64}
Poll a (owning) channel in a loop while it's alive, which will trigger any callbacks. This function should always be called on a channel for it to work properly. It will return:
nothing
if the channel was closed during the loop.- Otherwise the last result from
lib.ssh_channel_poll()
, which should be checked to see if it'sSSH_EOF
.
Throws
LibSSHException
: IfSSH_ERROR
is returned andthrow=true
.
Arguments
sshchan
: TheSshChannel
to poll.throw=true
: Whether to throw an exception ifSSH_ERROR
is returned.
Base.isassigned
— Methodisassigned(sshchan::LibSSH.SshChannel) -> Bool
Check if the channel holds a valid pointer to a lib.ssh_channel
.
Base.isopen
— Methodisopen(sshchan::LibSSH.SshChannel) -> Bool
Checks if the channel is open. Wrapper around lib.ssh_channel_is_open()
.
Base.close
— Methodclose(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 SshChannel
s. It will hold the close_lock
of the channel during execution.
Arguments
sshchan
: TheSshChannel
to 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: disconnected
error).
Base.eof
— Methodeof(sshchan::LibSSH.SshChannel) -> Bool
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
— Methodclosewrite(
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
: TheSshChannel
to 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: disconnected
error).
Base.iswritable
— Methodiswritable(sshchan::LibSSH.SshChannel) -> Bool
Check if the channel is writable.
Base.write
— Methodwrite(
sshchan::LibSSH.SshChannel,
data::AbstractString;
stderr
) -> Int64
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
— Methodwrite(
sshchan::LibSSH.SshChannel,
data::Vector{UInt8};
stderr
) -> Int64
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
— Typestruct SshProcessFailedException <: Exception
process::LibSSH.SshProcess
This is analogous to ProcessFailedException
.
LibSSH.SshProcess
— Typemutable struct SshProcess
out::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.wait
— MethodBase.success
— Methodsuccess(process::LibSSH.SshProcess) -> Bool
Check if the process succeeded.
Base.run
— Methodrun(
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 | bar
instead). - 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
.
Setting environment variables is supported, but will fail if the server forbids setting them.
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_verbosity
on aSession
.combine_outputs=true
: Write thestderr
command output to theIOBuffer
for the commandsstdout
. If this istrue
thenSshProcess.out
andSshProcess.err
will 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.Demo.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
/tmp
Base.read
— Methodread(
cmd::Union{Cmd, String},
session::LibSSH.Session
) -> Vector{UInt8}
Read the output from the command in bytes.
Base.read
— Methodread(
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.Demo.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
— Methodreadchomp(
cmd::Union{Cmd, String},
session::LibSSH.Session
) -> SubString{String}
readchomp()
for remote commands.
Base.success
— Methodsuccess(
cmd::Union{Cmd, String},
session::LibSSH.Session
) -> Bool
Check the command succeeded.
Direct port forwarding
LibSSH.Forwarder
— Typemutable struct Forwarder
remotehost::String
remoteport::Int64
localinterface::Sockets.IPAddr
localport::Int64
out::Union{Nothing, Sockets.TCPSocket}
_listen_server::Sockets.TCPServer
_listener_task::Union{Nothing, Task}
_clients::Vector{LibSSH._ForwardingClient}
_next_client_id::Int64
_session::LibSSH.Session
verbose::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.
LibSSH.Forwarder
— MethodForwarder(
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_verbosity
on aSession
).localinterface=IPv4(0)
: The interface to bindlocalport
on.
LibSSH.Forwarder
— MethodForwarder(
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
— MethodForwarder(f::Function, args...; kwargs...) -> Any
Do-constructor for a Forwarder
. All arguments are forwarded to the other constructors.
Base.close
— Methodclose(forwarder::LibSSH.Forwarder)
Close a Forwarder
. This will close all client channels and the listening local socket.