UNIX ssh script, running commands on remote server

2020-02-26 11:36发布

I would like to create a script that automatically logs into a remote server and grabs a file on the server. The script already logs into the server however the commands are not run on that machine. Once I disconnect from the remote server, the commands are run on the client machine.

!/bin/sh
ssh -o PreferredAuthentications=publickey brjones@server.com
cd ~/folder
"i would like to grab file and copy it to client machines folder"

EDIT: I am not sure if you noticed but I am used a passwordless connection to the remote server using ssh and keygeneration. I appreciate the ideas but I am looking to possibly pipe commands or run commands on the remote server with the script on the client. I realize that the remote server does not have access to the client script, however I was curious if it was possible to pipe the commands through the ssh connection.

10条回答
在下西门庆
2楼-- · 2020-02-26 12:13

If your goal is only to transfer files, you should use scp. But to execute some commands on the remote host without having a specific script on that remote host, you can simply use the stdin like this:

!/bin/sh
ssh -o PreferredAuthentications=publickey brjones@server.com << EOT
cd ~/folder
echo "hello" > hello.txt
...
EOT
查看更多
欢心
3楼-- · 2020-02-26 12:16

You should be using scp ("secure copy") rather than ssh ("secure shell").

查看更多
贼婆χ
4楼-- · 2020-02-26 12:19

Several people have already explained how to do the particular example you give better and easier.

If you really do need to script a remote interaction, you might consider using expect.

查看更多
Rolldiameter
5楼-- · 2020-02-26 12:19

If you want to invoke a script on remote host, which present on localhost

ssh remote Password@remoteHostname < localScript.sh

If you want to invoke a script which is already on remote host

ssh remote Password@remoteHostname "$PATH_OF_SCRIPT/remoteScript.sh"

查看更多
不美不萌又怎样
6楼-- · 2020-02-26 12:20

Also, if you don't want to have a script available on the remote server, try the following:

ssh thehost 'cd /tmp; ls; echo Hello world, I am `hostname`'

and for SCP-less copying:

ssh localhost 'cat /bin/bash' > local_bash
查看更多
成全新的幸福
7楼-- · 2020-02-26 12:31

In addition to the answer by Tiemen, of course you can pipe the commands from your local script with:

ssh thehost < commands.sh
查看更多
登录 后发表回答