Skip to content

Instantly share code, notes, and snippets.

@hcs42
Created July 8, 2016 15:19
Show Gist options
  • Save hcs42/96372a240ee7c41e9df8839318fa07f3 to your computer and use it in GitHub Desktop.
Save hcs42/96372a240ee7c41e9df8839318fa07f3 to your computer and use it in GitHub Desktop.
A script to evaluate an expression on an Erlang node
#!/usr/bin/env escript
%%! -name rpc@127.0.0.1
%% rpc is a script that connects to the given Erlang node using RPC and
%% evaluates an expression in it.
%%
%% Examples:
%%
%% rpc mynode@127.0.0.1 mycookie 'erlang:whereis(init)'
%% rpc mynode@127.0.0.1 mycookie erlang whereis '[init]'
-mode(compile).
main([NodeStr, CookieStr, ExprStr]) ->
Node = list_to_atom(NodeStr),
Cookie = list_to_atom(CookieStr),
Expr = string_to_expr(ExprStr),
erlang:set_cookie(Node, Cookie),
case rpc:call(Node, erl_eval, expr, [Expr, _Bindings = []]) of
{value, Value, _NewBindings} ->
io:format("~p~n", [Value]);
Other ->
io:format("~p~n", [Other])
end;
main([NodeStr, CookieStr, ModNameStr, FunNameStr, ArgsStr]) ->
Node = list_to_atom(NodeStr),
Cookie = list_to_atom(CookieStr),
ModName = list_to_atom(ModNameStr),
FunName = list_to_atom(FunNameStr),
Args = string_to_term(ArgsStr),
erlang:set_cookie(Node, Cookie),
Res = rpc:call(Node, ModName, FunName, Args),
io:format("~p~n", [Res]);
main(_) ->
io:format(
"Usage example:
$ rpc mynode@127.0.0.1 mycookie 'erlang:whereis(init)'
$ rpc mynode@127.0.0.1 mycookie erlang whereis '[init]'
").
string_to_term(String) ->
case erl_scan:string(String ++ ".") of
{ok, Tokens, _Loc} ->
case erl_parse:parse_term(Tokens) of
{ok, Term} ->
Term;
{error, Reason} ->
throw({error, Reason})
end;
{error, Reason, _Loc} ->
throw({error, Reason})
end.
string_to_expr(String) ->
case erl_scan:string(String ++ ".") of
{ok, Tokens, _Loc} ->
case erl_parse:parse_exprs(Tokens) of
{ok, [Expr]} ->
Expr;
{error, Reason} ->
throw({error, Reason})
end;
{error, Reason, _Loc} ->
throw({error, Reason})
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment