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

前端 未结 17 1555
南笙
南笙 2020-11-21 22:33

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 o

相关标签:
17条回答
  • 2020-11-21 22:49

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

    0 讨论(0)
  • 2020-11-21 22:53

    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.

    0 讨论(0)
  • 2020-11-21 22:54

    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).

    0 讨论(0)
  • 2020-11-21 22:55
    cat ./script.sh | ssh <user>@<host>
    
    0 讨论(0)
  • 2020-11-21 23:00
    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.

    0 讨论(0)
  • 2020-11-21 23:02

    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.

    0 讨论(0)
提交回复
热议问题