1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
|
-module(my_ssh). -author(kingwen0302). -version(1.0). -date('2016-03-15').
-export([exec/4]).
-spec exec(Host, Port, Options, Cmd) -> Return when Host :: string(), Port :: integer(), Options :: list(), Cmd :: string(), Return :: {ExitStatus, Result}, ExitStatus :: integer(), Result :: string().
exec(Host, Port, Options, Cmd) -> ssh:start(), {ok, Ref} = ssh:connect(Host, Port, Options), {ok, ChanID} = ssh_connection:session_channel(Ref, infinity), case ssh_connection:exec(Ref, ChanID, Cmd, infinity) of success -> {ExitStatus, ReturnStr} = wait(Ref), io:format("ExitStatus:~p~n", [ExitStatus]), io:format("ReturnStr:~n~s~n", [ReturnStr]), ok; _ -> error end.
wait(Ref) -> wait(Ref, 0, "").
wait(Ref, ExitStatus, Str) -> receive {ssh_cm, Ref, Msg} -> case Msg of {closed, _ChanID} -> {ExitStatus, Str}; {data, _ChanID, _, RecvStr} -> NewStr = io_lib:format("~s~s", [Str, RecvStr]), wait(Ref, ExitStatus, NewStr); {exit_status, _ChanID, Status} -> wait(Ref, Status, Str); _ -> wait(Ref, ExitStatus, Str) end end.
|