UNIX ssh script, running commands on remote server

时光怂恿深爱的人放手 提交于 2019-11-30 09:58:31

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

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

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

You should use ssh in this way to execute scripts on remote machines,

ssh user@server exec /path/to/script/script.sh

where script.sh is available on the server on the given path from the user login.


If the script is not present on the server but available on your local machine (and you do not have common NFS shared space between the two machines), you should send the script with scp like this,

scp script.sh user@server:/path/to/script/

Now, for your specific case of getting a server file you should just execute,

scp user@server:/path/to/file/filename .

like some other answers already suggest.

ssh in a script doesn't work like that. However it does have the capability to execute a command on a remote server by specifying the command as an argument to ssh, like:

ssh brjones@server.com do_foo.sh

will run the do_foo.sh script on the server

However for your situation it looks like what you are really looking for is SCP.

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

ssh thehost < commands.sh
J. Piel

scp? Remote is an appliance with a read only file system. I don't want to leave the script behind, or use multiple invocations of ssh to clean it up after or multiple invocations to execute it one line at a time. The list goes on...

great solution here by Yarek T:

You might have to play around a bit with quoting or escapes but it gets the job done, with a single connection to the remote and the script remaining local.

laginimaineb

Why not use scp?

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.

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"

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!