通过使用 SSH 命令,我们可以在远程服务器上运行命令,而无需登录到服务器 shell。
SSH 命令格式
# ssh remoteuser@remotehost remotecommand
假设我想在远程服务器 pk.testmail.com 上运行 ls 命令
geek@Earth:~$ ssh root@pk.testmail.com ls The authenticity of host ' pk.testmail.com (x.x.x.x)' can't be established. RSA key fingerprint is 7d:74:91:ed:30:1e:86:0b:69:c9:77:0b:72:0e:ad:4e. Are you sure you want to continue connecting (yes/no)? yes Warning: Permanently added 'pk.testmail.com' (RSA) to the list of known hosts. root@pk.testmail.com's password: anaconda-ks.cfg downloads install.log install.log.syslog
注意:当我们在远程服务器上运行任何命令时,默认情况下 ssh 不会分配伪终端。
要使用伪终端,我们必须在 ssh 命令中使用 -t 选项,如下所述。
geek@Earth:~$ ssh -t root@ pk.testmail.com ls root@pk.testmail.com's password: anaconda-ks.cfg downloads install.log install.log.syslog Connection to pk.testmail.com closed.
现在我们可以看到,命令输出将与我们登录远程服务器后运行相同的命令相同。
要在远程服务器上运行多个命令,请在命令之间使用分号,如下所示:
geek@Earth:~$ ssh -t root@ pk.testmail.com "ls ; df -h ; date ; cal" root@pk.testmail.com's password: anaconda-ks.cfg downloads install.log install.log.syslog server_invalid_mails_cleanup.sh Filesystem Size Used Avail Use% Mounted on /dev/vda 20G 6.9G 12G 37% / tmpfs 246M 0 246M 0% /dev/shm Mon Nov 10 00:52:12 EST 2014 November 2014 Su Mo Tu We Th Fr Sa 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 Connection to pk.testmail.com closed.
我们还可以使用 echo 命令在远程服务器上运行远程命令。
geek@Earth:~$ echo "ls" | ssh root@pk.testmail.com Pseudo-terminal will not be allocated because stdin is not a terminal. root@pk.testmail.com's password: anaconda-ks.cfg downloads install.log install.log.syslog
注意:我们不能在 ssh 命令中使用 -t 选项来运行使用 echo 命令的远程命令,因为不会分配伪终端,因为 stdin 不是终端。
使用 ssh 命令和 tar 命令在两台机器之间移动文件目录作为 scp 命令的替代。
示例解释如下:
geek@Earth:~$ tar -cvf - images/test1 | ssh root@ pk.testmail.com '(cd /tmp/; tar -xf -)' images/test1/ images/test1/7 images/test1/6 images/test1/5 images/test1/4 images/test1/9 images/test1/8 images/test1/3 images/test1/2 images/test1/1 root@pk.testmail.com's password:
现在文件上传到远程服务器。
检查远程服务器上的文件,如下所示。
[root@pk tmp]# ls -l images/ total 4 drwxrwxr-x 2 1000 1000 4096 Nov 10 01:02 test1 [root@pk tmp]# ls -l images/test1/ total 0 -rw-rw-r-- 1 1000 1000 0 Nov 10 01:02 1 -rw-rw-r-- 1 1000 1000 0 Nov 10 01:02 2 -rw-rw-r-- 1 1000 1000 0 Nov 10 01:02 3 -rw-rw-r-- 1 1000 1000 0 Nov 10 01:02 4 -rw-rw-r-- 1 1000 1000 0 Nov 10 01:02 5 -rw-rw-r-- 1 1000 1000 0 Nov 10 01:02 6 -rw-rw-r-- 1 1000 1000 0 Nov 10 01:02 7 -rw-rw-r-- 1 1000 1000 0 Nov 10 01:02 8 -rw-rw-r-- 1 1000 1000 0 Nov 10 01:02 9
日期:2020-09-17 00:10:51 来源:oir作者:oir