在我的.bashrc定义中我可以在命令行中使用的函数:
function mycommand() {
ssh user@123.456.789.0 cd testdir;./test.sh "$1"
}
Run Code Online (Sandbox Code Playgroud)
使用此命令时,只需cd在远程主机上执行该命令; 该test.sh命令在本地主机上执行.这是因为分号分隔了两个不同的命令:ssh命令和test.sh命令.
我尝试按如下方式定义函数(注意单引号):
function mycommand() {
ssh user@123.456.789.0 'cd testdir;./test.sh "$1"'
}
Run Code Online (Sandbox Code Playgroud)
我试图将cd命令和test.sh命令保持在一起,但是参数$1没有得到解决,与我给函数的内容无关.始终尝试执行命令
./test.sh $1
Run Code Online (Sandbox Code Playgroud)
在远程主机上.
如何正确定义mycommand,所以剧本test.sh正在改变进入目录后,在远程主机上执行testdir,具有传递给参数的能力mycommand来test.sh?
kon*_*box 70
这样做是这样的:
function mycommand {
ssh user@123.456.789.0 "cd testdir;./test.sh \"$1\""
}
Run Code Online (Sandbox Code Playgroud)
您仍然必须将整个命令作为单个字符串传递,但在该单个字符串中,您需要$1在将其发送到ssh之前进行扩展,因此您需要使用""它.
另一种实际做法的正确方法是使用printf %q正确引用参数.即使它有空格,单引号,双引号或任何其他可能对shell有特殊含义的字符,这也会使参数安全解析:
function mycommand {
printf -v __ %q "$1"
ssh user@123.456.789.0 "cd testdir;./test.sh $__"
}
Run Code Online (Sandbox Code Playgroud)
function,()没有必要.avi*_*amg 13
解决方案:您希望能够使用 ssh 协议远程连接到计算机并在外部触发/运行一些操作。
在 ssh 上使用一个-t标志,来自文档:
-t Force pseudo-terminal allocation.
This can be used to execute arbitrary screen-based programs on a remote machine, which can be very useful, e.g.when implementing menu services. Multiple -t options force tty allocation, even if ssh has no local tty.
公式:
ssh -i <key-path> <user>@<remote-machine> -t '<action>'
Run Code Online (Sandbox Code Playgroud)
示例:作为管理员,我希望能够远程连接到 ec2 机器,并针对原始状态下多台机器上的错误部署触发恢复过程,此外,您最好将此操作实现为使用 ips 作为参数并运行的自动化脚本在不同的机器上并行。
ssh -i /home/admin/.ssh/key admin@10.20.30.40 -t 'cd /home/application && make revert'
Run Code Online (Sandbox Code Playgroud)
我正在使用以下命令从本地计算机远程执行命令:
ssh -i ~/.ssh/$GIT_PRIVKEY user@$IP "bash -s" < localpath/script.sh $arg1 $arg2
Run Code Online (Sandbox Code Playgroud)
这是一个适用于 AWS 云的示例。场景是一些从自动缩放启动的机器需要在另一台服务器上执行一些操作,通过 SSH 传递新生成的实例 DNS
# Get the public DNS of the current machine (AWS specific)
MY_DNS=`curl -s http://169.254.169.254/latest/meta-data/public-hostname`
ssh \
-o StrictHostKeyChecking=no \
-i ~/.ssh/id_rsa \
user@remotehost.example.com \
<< EOF
cd ~/
echo "Hey I was just SSHed by ${MY_DNS}"
run_other_commands
# Newline is important before final EOF!
EOF
Run Code Online (Sandbox Code Playgroud)
恢复旧线程,但未列出这种非常干净的方法。
function mycommand() {
ssh user@123.456.789.0 <<+
cd testdir;./test.sh "$1"
+
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
134615 次 |
| 最近记录: |