1

I am trying to get the value of uname -r from a remote machine over ssh and use that value in my local script flow.

kern_ver=uname -r
sshpass -p "$passwd" ssh -o StrictHostKeyChecking=no root@$c 'kern_ver=echo \$kern_ver'

But looks like the value is not getting passed back to the local script flow .

1

2 Answers 2

7

Storing the command in the variable cmd is optional; you can hard-code the command as a string argument to ssh. The key is that you simply run the command on the remote host via ssh, and capture its output on the local host.

cmd="uname -r"
kern_ver=$(sshpass -p "$passwd" ssh -o StrictHostKeyChecking=no root@"$c" "$cmd")
Sign up to request clarification or add additional context in comments.

1 Comment

"hard-code" is an important point: If the command isn't entirely hardcoded but includes parameterized portions, more complex techniques are required to prevent shell injection attacks.
1

Capture is var=$(...), as always.

ssh is a bit interesting because it unconditionally invokes a remote shell, so working with completely arbitrary commands (as opposed to simple things like uname -r) requires a different technique:

filename="/path/to/name with spaces/and/ * wildcard characters *"
printf -v cmd_str '%q ' ls -l "$filename"
output=$(ssh "$host" "$cmd_str")

This way you can use arguments with spaces, and they'll be passed with correct quoting through to the remote system (with the caveat that non-printable characters may be quoted with bash-only syntax, so this is only guaranteed to work in cases where the remote shell is also bash).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.