How to execute a remote command and pass in local file as input?

Is it possible to do this:

ssh [email protected] command /path/to/file/on/local/machine

That is to say, I want to execute a remote command using a local file in one step, without first using scp to copy the file.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You missed just one symbol =)

ssh <a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="146167716654677b777f7160">[email protected]</a> command < /path/to/file/on/local/machine

Method 2

One way that works regardless of the command is to make the file available on the remote machine via a remote filesystem. Since you have an SSH connection:

  1. Establish a reverse SSH tunnel. See also SSH easily copy file to local system
  2. Mount a directory tree of your machine containing the file to share on the remote machine with SSHFS. (Example)

Method 3

# What if remote command can only take a file argument and not read from stdin? (1_CR)
ssh <a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7702041205370418141c1203">[email protected]</a> command < /path/to/file/on/local/machine
...
cat test.file | ssh <a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d6a3a5b3a496bbb7b5bebfb8b3">[email protected]</a> 'bash -c "wc -l <(cat -)"'  # 1_CR

As an alternative to bash process substitution <(cat -) or < <(xargs -0 -n 1000 cat) (see below) you can just use xargs and cat to pipe the contents of the specified files to wc -l (which is more portable).

# Assuming that test.file contains file paths each delimited by an ASCII NUL character 
# and that we are to count all those lines in all those files (provided by test.file).

#find . -type f -print0 > test.file
# test with repeated line count of ~/.bash_history file
for n in {1..1000}; do printf '%s00' "${HOME}/.bash_history"; done > test.file

# xargs & cat
ssh localhost 'export LC_ALL=C; xargs -0 -n 1000 cat | wc -l' <test.file

# Bash process substitution
cat test.file | ssh localhost 'bash -c "export LC_ALL=C; wc -l < <(xargs -0 -n 1000 cat)"'


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x