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

前端 未结 17 1553
南笙
南笙 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:39

    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 '''

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

    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

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

    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"
    
    0 讨论(0)
  • 2020-11-21 22:42

    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/

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

    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.

    0 讨论(0)
  • 2020-11-21 22:46
    <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)

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