On Using Neo4j-Shell with Basic-Auth Over Http on a Remote Server
Join the DZone community and get the full member experience.
Join For FreeAccessing your beloved Neo4j-Shell via RMI works ok on localhost or in your intranet. But over the internet you don’t really want to expose RMI ports.
So most installations of Neo4j, e.g. on EC2 use basic auth as simplest security measure.
Also the Neo4j hosting providers like GrapheneDB.com or GraphHost.com offer basic auth by default to “secure” access your Neo4j instance, hopefully also SSL soon.
How do you access the Neo4j Shell on the server from your usual terminal command line ?
If you remember, the Neo4j 1.9 WebAdmin, had a built in Neo4j-Shell tab. This one is still happy and alive and can be accessed via http://localhost:7474/webadmin.
And it uses a simple http endpoint to send shell commands to the server and receives the prompt and command output back.
So you can use curl to easily execute shell commands. And as curl supports basic-auth you have this part covered too.
It looks like this:
curl -s -H accept:application/json -H content-type:application/json \
-u username:password \
-d "{\"command\":\"schema\",\"engine\":\"shell\"}" \
http://localhost:7474/db/manage/server/console
results in a json array result containing the rendered text and the new prompt.
[ "No indexes\n\nNo constraints\n", "neo4j-sh (?)$ " ]
So you can execute any shell command or cypher statement (remember to end them with Semicolon “;”) across the wire.
To make it directly useable I hacked together a small script (a better version of this would use a language like perl, python, ruby or javascript or at least a json library like jq).
#!/bin/bash
# usage neo.sh [-h host:port] [-u user:pass] [cmd]
# end cypher statements with semicolon
# terminate read loop with ^d or return
HOST="localhost:7474"
if [ "$1" == "-h" ]; then
shift; HOST="$1";shift;
fi
AUTH=""
if [ "$1" == "-u" ]; then
shift; AUTH="-u $1";shift;
fi
URL="http://${HOST}/db/manage/server/console"
HEADERS=' -H accept:application/json -H content-type:application/json '
function run {
CMD="$@"
DATA="{\"command\":\"${CMD}\",\"engine\":\"shell\"}"
RES=`curl -s $HEADERS $AUTH -d "$DATA" "$URL"`
# bash substitution
RES=${RES#'[ "'}
PROMPT_PATTERN="\", \"neo4j-sh (*)$ \" ]"
RES=${RES%$PROMPT_PATTERN}
# continue reading, incomplete command
if [ "$RES" == "\", \"> \" ]" ]; then
return 1;
else
echo -e "${RES//\\\\n/\\n}"
return 0;
fi
}
P0="neo4j-sh (*)\$ "
if [ "$@" ]; then
run "$@";
exit $?
fi
read -p "$P0" CMD;
while [ "$CMD" ]; do
run "$CMD"
if [ $? == 0 ]; then
read -p "$P0" CMD;
else
#continue reading, incomplete command
read -p "> " CMD1;
CMD="${CMD} ${CMD1}"
fi
done
See also this GitHub Gist for a ready-to use version of my hackey script.
Published at DZone with permission of , DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments