How to use SSH to run a local shell script on a remote machine?
Asked Answered
L

24

1419

I have to run a local shell script (windows/Linux) on a remote machine.

I have SSH configured on both machine A and B. My script is on machine A which will run some of my code on a remote machine, machine B.

The local and remote computers can be either Windows or Unix based system.

Is there a way to run do this using plink/ssh?

Luminiferous answered 20/11, 2008 at 11:44 Comment(8)
The same question is already on serverfault: serverfault.com/questions/215756/… So there's probably no point in migrating this question.Peridotite
The question on Server Fault doesn't have as many answers though. Maybe this question should replace that one.Guitarist
I like this answer personally: unix.stackexchange.com/questions/87405/…Orchard
Furthermore it should obviously be on topic since ssh is a prime tool for software development.Kindle
Coffee and ssh questions do not share the same degree of off-topicness on SO. Voted for reopen.Mystery
can somebody comment on the ENDSSH tag, please?Tasteful
@adam-lear, I think this question should be opened. I modified the question to make it such that it fits stackoverflow. The most popular answer here doesnt actually work if you are trying to run a local script on a remote Widows machine and if it has multiple lines. I did figure out a way, and would love to provide the solution. Even though there does exist another post on serverfault, because of the popularity of this question, most people are going to come here.. so making sure that this question is uptodate will be very helpful for visitors.Fellmonger
@Fellmonger That's fair. I closed this question unilaterally in my not-quite-two-months as a community moderator. It's not a hill I would want to die on now. :) I'll reopen, although that's not a guarantee that it'll stay open if the community in general disagrees. If it gets closed again, I suggest taking it to Meta Stack Overflow for a discussion.Thekla
A
1364

If Machine A is a Windows box, you can use Plink (part of PuTTY) with the -m parameter, and it will execute the local script on the remote server.

plink root@MachineB -m local_script.sh

If Machine A is a Unix-based system, you can use:

ssh root@MachineB 'bash -s' < local_script.sh

You shouldn't have to copy the script to the remote server to run it.

Aegeus answered 28/4, 2010 at 20:41 Comment(24)
is there an advantage to using the -s option? this man page leads me to believe that it will process standard input when it's done processing options, whether -s is used or not.Homey
@asia1281 There's no advantage; I chose this technique since it seemed more explicit. It's probably safe to omit the '-s'.Aegeus
For a script that requires sudo, run ssh root@MachineB 'echo "rootpass" | sudo -Sv && bash -s' < local_script.sh.Randi
@Randi remember to start the command with a 'space' to skip the history (P.S. you need to have HISTCONTROL=ignoreboth or ignorespace to make it work)Shimberg
@Randi in what situations would you need sudo if you are already logging in as root?Baseman
@Agostino, you can add parameters like this: ssh root@MachineB ARG1="arg1" ARG2="arg2" 'bash -s' < local_script.sh Credits fully go to @chubbsondubs' answer below.Defray
It seems the $PATH environment variable is not applied?Libratory
@ElgsQianChen I'm not sure what you're asking. Do you want the path from the local machine to apply to the remote machine? Or do you want some PATH that's normally present on the remote machine to be honored? Regardless, what you need to do is determine where that PATH is set, why you expect it to be set when executing a remote command, and where your expectation is violated, which would best be addressed in a separate question.Aegeus
I want the $PATH on the remote machine to be set. Finally I fond the solution, to add the export statements near the top of ~/.bashrc.Libratory
@SpencerBoucher I don't think that's possible. At least in the Unix case, the stdin on the local machine is already handling the stream of the script. I suggest posting a separate question and detailing what you're trying to accomplish.Aegeus
The above methods are not working for me if I have to execute the local sh file onto a remote machine which requires pem file for authenticationAcantho
Jast joking: what will happen if you will have in local_script.sh "ssh root@MachineB 'bash -s' < local_script.sh" ;)Wandering
@JasonR.Coombs.. I am trying to run a .bat file (similar to the local_scrip.sh) on a Windows machine with your exact command. However, I am finding that if the .bat file has more than 1 line, the second line doesnt get executed. Have you found this to be true?Fellmonger
@alpha_989: It's been a very long time since I've tried running on SSH server on Windows. I suspect it's a defect or limitation of your SSH server on Windows that it won't take more than one line of input from the SSH command when run non-interactively. I suggest creating a new question and describe exactly which server and client you're using, what you expect, and what you get instead.Aegeus
yeah.. I figured it out, but couldn't post an answer here as this question seems to be closed: serverfault.com/a/908587/443721Fellmonger
Just a quick note: Use the --login option for bash to behave like a normal login shell (e.g. paths are set like defined in ~/.bash-profile etc.). Use it like ssh root@MachineB 'bash -ls' < local_script.shIble
@YvesVanBroekhoven This is old, but the very point of -s is to be able to pass arguments to a script that is sourced through stdin: ssh root@MachineB 'bash -s arg1 arg2' < local_script.sh. Omitting -s would cause arg1 to be interpreted as the remote script to execute with arg2 as its first argument. There is no need to use environment variables.Chickabiddy
This answer should the accepted answer and on top of all the others. It's the only one that corresponds exactly to the problem, and it's short and easy. I had to struggle for about an hour considering all the others, until I saw this one.Floorwalker
Used the following to provide the password from outside the server and to not show the default prompt: echo "password" | ssh user@server 'sudo --prompt="" --stdin bash -s' < local.shApodosis
Is it possible to extend this ability further by running the example local_script.sh via a bastion as well?Pentateuch
This works to use a bastion: ssh -o ProxyCommand="ssh $host1 -W %h:%p" $host2 "bash -s" < local.shPentateuch
when forwarding stdin like this, is it encrypted? eg if we pass "secret=var bash -s" < local.sh is this safe?Pentateuch
That probably deserves its own question.Aegeus
@JasonR.Coombs What if local_script.sh relies on a local_exe? If I directly run this command, it says local_exe not found.Mytilene
A
743

This is an old question, and Jason's answer works fine, but I would like to add this:

ssh user@host <<'ENDSSH'
#commands to run on remote host
ENDSSH

This can also be used with su and commands which require user input. (note the ' escaped heredoc)

Since this answer keeps getting bits of traffic, I would add even more info to this wonderful use of heredoc:

You can nest commands with this syntax, and that's the only way nesting seems to work (in a sane way)

ssh user@host <<'ENDSSH'
#commands to run on remote host
ssh user@host2 <<'END2'
# Another bunch of commands on another host
wall <<'ENDWALL'
Error: Out of cheese
ENDWALL
ftp ftp.example.com <<'ENDFTP'
test
test
ls
ENDFTP
END2
ENDSSH

You can actually have a conversation with some services like telnet, ftp, etc. But remember that heredoc just sends the stdin as text, it doesn't wait for response between lines

I just found out that you can indent the insides with tabs if you use <<-END!

ssh user@host <<-'ENDSSH'
    #commands to run on remote host
    ssh user@host2 <<-'END2'
        # Another bunch of commands on another host
        wall <<-'ENDWALL'
            Error: Out of cheese
        ENDWALL
        ftp ftp.example.com <<-'ENDFTP'
            test
            test
            ls
        ENDFTP
    END2
ENDSSH

(I think this should work)

Also see http://tldp.org/LDP/abs/html/here-docs.html

Abalone answered 6/10, 2010 at 13:11 Comment(16)
you can temporize a bit by adding lines such as: # $(sleep 5)Veda
note that with single quotes around the terminator (<<'ENDSSH'), the strings will not be expanded, variables will not be evaluated. You can also use <<ENDSSH or <<"ENDSSH" if you want expansion.Outsider
Expect can be used when you need to automate interactive commands like FTP.Feria
Now how could I send a HEREDOC to a remote host over SSH, from a shell script locally?Strephon
Note that I had a Pseudo-terminal will not be allocated because stdin is not a terminal. message. One has to use ssh with -t -t params to avoid that. See this thread on SOCaudle
This option didn't work for me as each line executed as if called with ssh user@server 'line', while I required all lines executed in a single environment. With Jason's answer everything works as required.Cosentino
If you're trying to use the <<-'END' syntax, be sure your heredoc ending delimiter is indented using TABs, not spaces. Note that copy/paste from stackexchange will give you spaces. Change those to tabs and the indent feature should work.Meal
I upvoted this and my vote was counted as down vote.... weird, now I can't change itInexpiable
If password requested during ssh login then all commands will be spit out and interpreted as input.Intussusception
if i am using <<ENDSSH (without quotes). and inside running a command that uses awk's variables say NR. how do i escape the NR variable. \NR doesn't workPindling
On MacOS, ENDSSH, ENDFTP etc, should be write at beginning of line.Otherwise, a warning -bash: line 3: ENDSSH: command not found will be output.Pahlavi
Big thanks to Lorance Chen for your information about difference in MacOS - I had this problem now, so I think that it should be added into @Yarek TAbacist
The only thing I can criticize in this answer is its link to the ABS "documentation" -- the whole reason the Wooledge BashGuide was written was to have something less riddled with bad-practice examples than the ABS, forcing us denizens of the freenode #bash IRC channel to help people unlearn bad habits they picked up there.Mendez
Heredocs are great but it is worth mentioning that this method works if you know the accounts shell or make sure you only use POSIX syntax. If you are not sure, adding the "bash -s" before the script is safer.Proa
@Outsider It is incorrect to say that <<"ENDSSH" can be used if you want expansion. Expansions will not occur in a HEREDOC if any part of the word representing the delimiter is quoted.Blinders
I wrote a script that uses this heredoc method. How can I prevent all the commands in the heredoc from being echoed on the machine sending the commands?Compatible
P
270

Also, don't forget to escape variables if you want to pick them up from the destination host.

This has caught me out in the past.

For example:

user@host> ssh user2@host2 "echo \$HOME"

prints out /home/user2

while

user@host> ssh user2@host2 "echo $HOME"

prints out /home/user

Another example:

user@host> ssh user2@host2 "echo hello world | awk '{print \$1}'"

prints out "hello" correctly.

Panhellenism answered 20/11, 2008 at 12:25 Comment(3)
However be aware of the following: ssh user2@host 'bash -s' echo $HOME /home/user2 exitGoodhumored
Just to add that in for loops running in ssh session the loop variable must not be escaped.Deficit
In many situations, the sane way to fix your last example would be ssh user2@host2 'echo hello world' | awk '{ print $1 }' i.e. run the Awk script locally. If the remote command produces an immense about of output, you want to avoid copying it all back to the local server, of course. Incidentally, single quotes around the remote command avoid the need for any escaping.Fungi
E
174

This is an extension to YarekT's answer to combine inline remote commands with passing ENV variables from the local machine to the remote host so you can parameterize your scripts on the remote side:

ssh user@host ARG1=$ARG1 ARG2=$ARG2 'bash -s' <<'ENDSSH'
  # commands to run on remote host
  echo $ARG1 $ARG2
ENDSSH

I found this exceptionally helpful by keeping it all in one script so it's very readable and maintainable.

Why this works. ssh supports the following syntax:

ssh user@host remote_command

In bash we can specify environment variables to define prior to running a command on a single line like so:

ENV_VAR_1='value1' ENV_VAR_2='value2' bash -c 'echo $ENV_VAR_1 $ENV_VAR_2'

That makes it easy to define variables prior to running a command. In this case echo is our command we're running. Everything before echo defines environment variables.

So we combine those two features and YarekT's answer to get:

ssh user@host ARG1=$ARG1 ARG2=$ARG2 'bash -s' <<'ENDSSH'...

In this case we are setting ARG1 and ARG2 to local values. Sending everything after user@host as the remote_command. When the remote machine executes the command ARG1 and ARG2 are set the local values, thanks to local command line evaluation, which defines environment variables on the remote server, then executes the bash -s command using those variables. Voila.

Entrain answered 9/9, 2011 at 15:0 Comment(3)
Note that if you want to pass args like -a then you can use --. e.g. 'ssh user@host -- -a foo bar 'bash -s' <script.sh'. And the args can also go after the redirect e.g. 'ssh user@host 'bash -s' <script.sh -- -a foo bar'.Labrie
If any of the env var values contain spaces, use: ssh user@host "ARG1=\"$ARG1\" ARG2=\"$ARG2\"" 'bash -s' <<'ENDSSH'...Soddy
Like I wrote in another comment, the very point of using -s is to be able to apply arguments to scripts that are sourced through stdin. I mean, you may as well omit it if you're not going to use it. If you do use it, there is no reason to use environment variables: ssh user@host 'bash -s value1 value2' <<< 'echo "$@"'Chickabiddy
G
113
<hostA_shell_prompt>$ ssh user@hostB "ls -la"

That will prompt you for password, unless you have copied your hostA user's public key to the authorized_keys file on the home of user .ssh's directory. That will allow for passwordless authentication (if accepted as an auth method on the ssh server's configuration)

Gaddis answered 20/11, 2008 at 11:53 Comment(3)
Voted you up. This is a valid solution. Obviously, the keys must be protected, but they can also be invalidated just like a password via the server side.Caswell
I don't think this answers the question. The example shows how to run a remote command, but not how to execute a local script on a remote machine.Aegeus
Not certain but can't you pipe your script on hostA to run on hostB using this method?Enact
A
28

I've started using Fabric for more sophisticated operations. Fabric requires Python and a couple of other dependencies, but only on the client machine. The server need only be a ssh server. I find this tool to be much more powerful than shell scripts handed off to SSH, and well worth the trouble of getting set up (particularly if you enjoy programming in Python). Fabric handles running scripts on multiple hosts (or hosts of certain roles), helps facilitate idempotent operations (such as adding a line to a config script, but not if it's already there), and allows construction of more complex logic (such as the Python language can provide).

Aegeus answered 26/1, 2011 at 16:17 Comment(0)
S
25
cat ./script.sh | ssh <user>@<host>
Scherzo answered 11/8, 2019 at 23:28 Comment(2)
Interestingly, this method of 'cat script.sh | ssh user@host' is the only one that is working for me to run a shell script on another host. the 'bash' < script.sh method is not working correctly, but I didn't spend time troubleshooting that. I even copied the script to the remote host, and I see 'file not found', even though if I login to the host and run the script, it works.Rustcolored
How about cat ./script.sh | ssh -i ~\\.ssh\\id_rsa <user>@<host> 'bash -'Carrageen
D
15
chmod +x script.sh    
ssh -i key-file [email protected] < ./script.sh
Disunite answered 1/12, 2020 at 13:30 Comment(1)
I don't think the chmod +x is necessary or useful in this case. The script isn't executed on the local host, it's read on the local host, and only its content is sent to the remote host and executed there. The remote host doesn't even know the content came from a file and thus doesn't care about the permissions of the file.Cicero
P
11

Try running ssh user@remote sh ./script.unx.

Palocz answered 18/12, 2009 at 21:16 Comment(2)
This only works if the script is in the default (home) directory on the remote. I think the question is how to run a script stored locally on the remote.Egor
ssh username@ip "chmod +x script.sh" <br/> ssh username@ip "path to sh file in remote host"Prisage
I
8

Assuming you mean you want to do this automatically from a "local" machine, without manually logging into the "remote" machine, you should look into a TCL extension known as Expect, it is designed precisely for this sort of situation. I've also provided a link to a script for logging-in/interacting via SSH.

https://www.nist.gov/services-resources/software/expect

http://bash.cyberciti.biz/security/expect-ssh-login-script/

Iron answered 20/11, 2008 at 12:10 Comment(0)
B
7
ssh user@hostname ". ~/.bashrc;/cd path-to-file/;. filename.sh"

highly recommended to source the environment file(.bashrc/.bashprofile/.profile). before running something in remote host because target and source hosts environment variables may be deffer.

Barnard answered 14/8, 2019 at 12:54 Comment(2)
This does not explain how to move a local script to the remote host.Anderegg
it seems that a space is missing before ~/.bashrcClayborne
R
5

I use this one to run a shell script on a remote machine (tested on /bin/bash):

ssh deploy@host . /home/deploy/path/to/script.sh
Remonstrant answered 10/11, 2018 at 20:6 Comment(0)
R
4

If the script is short and is meant to be embedded inside your script and you are running under bash shell and also bash shell is available on the remote side, you may use declare to transfer local context to remote. Define variables and functions containing the state that will be transferred to the remote. Define a function that will be executed on the remote side. Then inside a here document read by bash -s you can use declare -p to transfer the variable values and use declare -f to transfer function definitions to the remote.

Because declare takes care of the quoting and will be parsed by the remote bash, the variables are properly quoted and functions are properly transferred. You may just write the script locally, usually I do one long function with the work I need to do on the remote side. The context has to be hand-picked, but the following method is "good enough" for any short scripts and is safe - should properly handle all corner cases.

somevar="spaces or other special characters"
somevar2="!@#$%^"
another_func() {
    mkdir -p "$1"
}
work() {
    another_func "$somevar"
    touch "$somevar"/"$somevar2"
}
ssh user@server 'bash -s' <<EOT
$(declare -p somevar somevar2)    # transfer variables values
$(declare -f work another_func)   # transfer function definitions
work                              # call the function
EOT
Rapping answered 7/2, 2021 at 9:45 Comment(0)
E
3

It's easiest to explain a solution for what the OP is asking for by using a demo:

  1. Create a local script however you want. You don't need to set the executable bit. In this example, I use a here document:

    cat <<END >demo.sh
    > echo "Script executed on ${HOSTNAME} with args: $@"
    > END
    
  2. Using ssh run the local script on the remote host.

    Both ways work:

    cat demo.sh | ssh host bash -s -- hello world
    

    or

    ssh host bash -s -- hello world < demo.sh
    

    In either case, you'll see the following output (with HOSTNAME replaced with the remote hostname):

    Script executed on HOSTNAME with args: hello world
    

Notes

  • Using -s tells bash to read from stdin (see 6.1 Invoking Bash).

  • Using -- ensures the following arguments are passed to the script, not to bash.

Emphatic answered 24/6, 2023 at 5:34 Comment(1)
That's the cleanest answer, if you intend to use parameters with the script.Boomerang
P
2

This bash script does ssh into a target remote machine, and run some command in the remote machine, do not forget to install expect before running it (on mac brew install expect )

#!/usr/bin/expect
set username "enterusenamehere"
set password "enterpasswordhere"
set hosts "enteripaddressofhosthere"
spawn ssh  $username@$hosts
expect "$username@$hosts's password:"
send -- "$password\n"
expect "$"
send -- "somecommand on target remote machine here\n"
sleep 5
expect "$"
send -- "exit\n"
Phifer answered 30/5, 2018 at 9:22 Comment(1)
this is great if you must use passwords ... however for benefit of anyone watching at home any ssh command should use a pair of public+private keys not passwords ... once in place update your ssh server to shut off passwords entirelyGarniture
P
2

if you wanna execute command like this temp=`ls -a` echo $temp command in `` will cause errors.

below command will solve this problem ssh user@host ''' temp=`ls -a` echo $temp '''

Patchouli answered 21/9, 2018 at 3:31 Comment(0)
F
1

The answer here (https://mcmap.net/q/45287/-how-to-use-ssh-to-run-a-local-shell-script-on-a-remote-machine) works great if you're trying to run a script on a remote linux machine using plink or ssh. It will work if the script has multiple lines on linux.

**However, if you are trying to run a batch script located on a local linux/windows machine and your remote machine is Windows, and it consists of multiple lines using **

plink root@MachineB -m local_script.bat

wont work.

Only the first line of the script will be executed. This is probably a limitation of plink.

Solution 1:

To run a multiline batch script (especially if it's relatively simple, consisting of a few lines):

If your original batch script is as follows

cd C:\Users\ipython_user\Desktop 
python filename.py

you can combine the lines together using the "&&" separator as follows in your local_script.bat file: https://mcmap.net/q/13758/-how-do-i-run-two-commands-in-one-line-in-windows-cmd:

cd C:\Users\ipython_user\Desktop && python filename.py

After this change, you can then run the script as pointed out here by @JasonR.Coombs: https://mcmap.net/q/45287/-how-to-use-ssh-to-run-a-local-shell-script-on-a-remote-machine with:

`plink root@MachineB -m local_script.bat`

Solution 2:

If your batch script is relatively complicated, it may be better to use a batch script which encapsulates the plink command as well as follows as pointed out here by @Martin https://mcmap.net/q/46261/-open-ssh-tunnel-via-plink-and-run-r-scripts-via-command-line-batch-file:

rem Open tunnel in the background
start plink.exe -ssh [username]@[hostname] -L 3307:127.0.0.1:3306 -i "[SSH
key]" -N

rem Wait a second to let Plink establish the tunnel 
timeout /t 1

rem Run the task using the tunnel
"C:\Program Files\R\R-3.2.1\bin\x64\R.exe" CMD BATCH qidash.R

rem Kill the tunnel
taskkill /im plink.exe
Fellmonger answered 21/4, 2018 at 0:44 Comment(0)
L
1

You can use runoverssh:

sudo apt install runoverssh
runoverssh -s localscript.sh user host1 host2 host3...

-s runs a local script remotely


Useful flags:
-g use a global password for all hosts (single password prompt)
-n use SSH instead of sshpass, useful for public-key authentication

Leakey answered 1/9, 2019 at 17:9 Comment(0)
L
1

It is unclear if the local script uses locally set variables, functions, or aliases.

If it does this should work:

myscript.sh:

#!/bin/bash

myalias $myvar
myfunction $myvar

It uses $myvar, myfunction, and myalias. Let us assume they is set locally and not on the remote machine.

Make a bash function that contains the script:

eval "myfun() { `cat myscript.sh`; }"

Set variable, function, and alias:

myvar=works
alias myalias='echo This alias'
myfunction() { echo This function "$@"; }

And "export" myfun, myfunction, myvar, and myalias to server using env_parallel from GNU Parallel:

env_parallel -S server -N0  --nonall myfun ::: dummy
Lek answered 24/1, 2021 at 23:34 Comment(0)
F
0

If it's one script it's fine with the above solution.

I would set up Ansible to do the Job. It works in the same way (Ansible uses ssh to execute the scripts on the remote machine for both Unix or Windows).

It will be more structured and maintainable.

Ferree answered 28/7, 2020 at 9:1 Comment(0)
D
0

Extending answer from @cglotr. In order to write inline command use printf, it useful for simple command and it support multiline using char escaping '\n'

example :

printf "cd /to/path/your/remote/machine/log \n tail -n 100 Server.log" | ssh <user>@<host> 'bash -s'

See don't forget to add bash -s

Diatessaron answered 1/8, 2022 at 2:56 Comment(0)
C
0

I created a solution that works better for me by combining the use of a heredoc from Yarek T's answer with the piped cat method from cglotr's answer along with some other tricks for non-interactive login (using sshpass), using variables from the local and remote host in the script, and enabling sudo commands. The code is longer just because it includes some additional tricks that are likely desired, but the original questioner didn't ask for them.

The problem I have with Yarek's answer is that all the warnings and commands in the heredoc print to the screen. The problem I have with cglotr's answer is that is requires a script file and a complex command with additional interaction to execute the script. With my solution, I write a script that does everything by simply calling the script with the remote host IP address as the first argument like this:

./MYSCRIPT REMOTE_IP_ADDRESS

The script to be run on the remote host is saved to a variable within the script on the local host using a heredoc so that you don't need to do any quote escaping. Then, the variable containing the script is echo piped to sshpass. Be sure to indent the commands with tabs and not spaces (you'll get spaces instead of tabs when you copy the code). Here is an example of the remote script within the local script.

!/bin/bash
# Input argument 1 should be the target host IP address (required)
RX_IP="/(\b25[0-5]|\b2[0-4][0-9]|\b[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}/"
IS_IP=$(echo $1 | sed -nr "${RX_IP}p" | wc -l)
if (( $IS_IP )); then
    USERNAME=remoteuser
    HOSTNAME=$1
    # Export the SSH password to environment variable for sshpass and sudo.
    # The space before the command prevents saving the command to history.
     export SSHPASS=mypassword;
    while read -r -d '' SCRIPT <<-EOS
        # Enable sudo commands with the following command.
        # The space before echo prevents saving the command to history.
         echo $SSHPASS | sudo -Sv
        # Do stuff here. Escape variables to be be accessed on the remote host.
        # For example, escape print variable in an awk command:
        # This command lists all USB block device partitions.
        ls -l /dev /dev/mapper | awk '/^b/ && /sd[a-z][1-9]/ {print \$10}'
        exit
    EOS
    echo "$SCRIPT" | sshpass -e ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null ${USERNAME}@${HOSTNAME} &>/dev/null
    echo 'DONE'
else
    echo "Missing IP address of target host."
    echo "Usage: ./SCRIPT_NAME IP_ADDRESS
fi

You need to install sshpass on the local host like this (for Debian based distros).

sudo apt install sshpass
Compatible answered 25/2, 2023 at 2:2 Comment(0)
P
-1

There is another approach ,you can copy your script in your host with scp command then execute it easily .

Parsifal answered 2/8, 2022 at 8:17 Comment(0)
C
-20

First, copy the script over to Machine B using scp

[user@machineA]$ scp /path/to/script user@machineB:/home/user/path

Then, just run the script

[user@machineA]$ ssh user@machineB "/home/user/path/script"

This will work if you have given executable permission to the script.

Commix answered 20/11, 2008 at 11:44 Comment(6)
hi i applied recommended suggession but it give me following error [oracle@node1 ~]$ ssh oracle@node2:./home/oracle/au/fs/conn.sh ssh: node2:./home/oracle/au/fs/conn.sh: Name or service not known [oracle@node1 ~]$Evacuate
'ssh oracle@node2:./home/oracle/au/fs/conn.sh'? Wrong command line, the command name should be separated from the user@host part with a space, not a colon.Heterogynous
I'm downvoting this because it's primary claim that it can't be run without copying it over is incorrect.Aegeus
It would have been helpful is Jason added why that's incorrect instead of simply stating the fact. Unhelpful.Blastocyst
[user@machineA]$ ssh root@MachineB 'bash -s' < /machinea/path/to/scriptSherer
and yet this is better than most answersAlford

© 2022 - 2024 — McMap. All rights reserved.