Har*_*rry 6 linux shell bash shell-script sshpass
有没有办法在 中使用多个命令sshpass,我尝试了不同的组合,但它会引发错误。
$ sudo sshpass -p $password ssh -t -oStrictHostKeyChecking=no $username@$ipaddress << EOF
command_one
command_two
command_three
EOF
Run Code Online (Sandbox Code Playgroud)
什么是正确和准确的命令,如果可能,请给我一个例子。
您的解决方案在使用或不使用 sshpass 的情况下都适用,如果它对您不起作用,则可能有其他问题。
另请注意,您应该始终引用每个变量。
此外,您不应轻易禁用stricthostkeychecking。如果您的主机密钥经常更改,则您的服务器可能已被盗用
不过,这里有一些方法可以实现您的目标:
使用命令分隔符 ( ;, &&, ||)
sshpass -p "$password" ssh -t -oStrictHostKeyChecking=no "$username@ipaddress" 'command_one; command_two; command_three'
Run Code Online (Sandbox Code Playgroud)
使用 here-doc(单引号 EOF 在远程主机上扩展任何变量/命令替换):
sshpass -p "$password" ssh -t -oStrictHostKeyChecking=no "$username@ipaddress" <<EOF
command_one
command_two
command_three
EOF
Run Code Online (Sandbox Code Playgroud)
使用单独的文件:
文件.sh
command_one
command_two
command_three
Run Code Online (Sandbox Code Playgroud)
然后像这样执行:
cat file.sh | sshpass -p "$password" ssh -t -oStrictHostKeyChecking=no "$username@ipaddress"
Run Code Online (Sandbox Code Playgroud)
使用 ssh 隧道:
sshpass -p "$password" ssh -f -L 3306:localhost:3306 "$username@ipaddress" sleep 300 # This will open a tunnel to the remote host and hold it open for 5 minutes
ssh -T "$username@ipaddress" 'command_one'
ssh -T "$username@ipaddress" 'command_two'
ssh -T "$username@ipaddress" 'command_three'
Run Code Online (Sandbox Code Playgroud)
像这样尝试:
$ sudo sshpass -p $password ssh -t -oStrictHostKeyChecking=no $username@$ipaddress << EOF
command_one;
command_two;
command_three;
EOF
Run Code Online (Sandbox Code Playgroud)
我做了上面的,它工作正常。