SSH远程执行命令
SSH是Linux下进行远程连接的基本工具,其实除了远程连接之外还可以直接远程执行命令,再配合设置ssh互相信任,可以为自动化打个基础

1、远程执行命令
-
执行无需交互的命令
ssh username@ip "command",如ssh root@192.168.0.4 "pwd"![]()
如果要执行多条命令,可以用分号区分:
ssh root@192.168.0.4 "pwd; echo 'hello'" -
执行需要交互的命令
如果直接执行类似于ssh username@ip "top"和要求输入密码之类的,这样的会交互的命令会报错。因为这种需要交互的命令都是需要一个TTY的,那我们可以通过参数-t来实现:![]()
2、远程执行脚本
-
执行本地的脚本
基础的命令是:ssh username@ip < script.sh,若是想要传递本地的参数,需要添加'bash -s'的参数,即:ssh username@ip 'bash -s' < script.sh parameter,如本地存在脚本test.sh,内容如下:#!/bin/bash pwd ls echo $1-
不带参数执行
ssh root@192.168.0.4 < test.sh![]()
-
带参数执行
ssh root@192.168.0.4 < test.sh hello![]()
-
用
'bash -s'带参数执行ssh root@192.168.0.4 'bash -s' < test.sh hello![]()
-
-
执行远程服务器上的脚本
-
直接执行下面的命令:
ssh username@ip "/root/script.sh",注意脚本要写绝对路径,如:
ssh root@192.168.0.4 "/root/test.sh"![]()
-
加上参数的话是
ssh username@ip "/root/script.sh parameter",如:
ssh root@192.168.0.4 "/root/test.sh hello"![]()
-








浙公网安备 33010602011771号