execute part of shell script on remote machine

2020-05-04 17:48发布

I am logging into remote machine through shell script (by placing ssh command in script). After ssh command ,The remaining lines of the script are getting executed on the current machine rather than remote machine. How to make the rest of shell script lines execute on remote machine.?

Lets say this is my script

ssh username@ip-address 
ls
whoami
----

The rest of lines after ssh should execute on remote machine rather than the current machine. How to achieve this?

标签: linux shell ssh
4条回答
地球回转人心会变
2楼-- · 2020-05-04 18:25

ssh -t user@remotehost 'uptime' user@remotehost's password: 23:35:33 up 2:05, 3 users, load average: 0.79, 0.52, 0.60 Connection to remote closed.

When you specify -t, it opens the terminal in remote machine and execute the command.

查看更多
Evening l夕情丶
3楼-- · 2020-05-04 18:33

Is your login passwordless.

If yes, you can just use pipe to execute the statement on the remote machine

like:

cat myshellscript.sh | ssh blah@blah.com -q
查看更多
唯我独甜
4楼-- · 2020-05-04 18:34

One possible solution would be to use a heredoc as in the following example:

$ ssh example.foo.com -- <<@@
> ls /etc/
> cat /etc/passwd
> @@

Basically everything between the @@ on the first line and the last line will be executed on the remote machine.

You could also use the contents of a file by either reading the contents of the file into a variable:

$ MYVAR=`cat ~/foo.txt`
$ ssh example.foo.com -- <<@@
> $MYVAR
> @@

or by simply performing the same action inside the heredoc:

$ ssh example.foo.com -- <<@@
> `cat ~/foo.txt`
> @@
查看更多
叼着烟拽天下
5楼-- · 2020-05-04 18:36

Use ssh command with -t options. For example:

ssh -t myremotehost 'uptime'
name@myremotehost's password: 
10:14:14 up 91 days, 21:20,  5 users,  load average: 0.20, 0.35, 0.36
查看更多
登录 后发表回答