ssh 远程执行命令/remote 执行

列举一些常见的 ssh 远程执行命令的方法
更新于: 2023-02-02 08:51:24

cheatsheet

Various ways to execute commands remotely using SSH.

PurposeSyntaxExamples
Single-line ssh command
单行命令执行
ssh $user@$host command

                        

ssh admin@ec2-server uptime

                   

Executing several commands
多条命令执行
ssh user@server "command1; command2; script1"

                        

ssh vivek@linode-server "ls /etc/resolv.conf; date"

                   

Running a command with sudo
带 sudo 的方式执行命令
ssh -t user@host sudo command

                        

ssh -t jobs@backup sudo /scripts/backup.sh

                   

Run commands from a local filessh user@hostname < file

                        

cat cmd.txt
date
git clone url
cd project
makessh vivek@ls.www-db-1 < cmds.txt

                   

Use Heredoc bash feature to run many commandsssh -T $HOST << EOL

                        

ssh -T admin@freebsdnas << EOL
uptime
date
df -H
echo "$var"
echo "$HOSTNAME"
EOL

                                           

# 也可以使用短名
ssh -T bio14 << EOL
 ls -alh
 pwd
EOL

                   

Multi-line command using Heredoc when you need to assign variablesssh -T box1<<'EOL'

                        

ssh -T vivek@server1<<'ENDSSH'
var=$(date)
echo "$var"
ENDSSH

                   

参考