免密操控 免密操控不可以逆向,即可以一个主控方对应多个被控方,但不可以一个被控方对应多个主控方。
以下以 gitlab-runner 账户远程免密登录 root@192.168.56.100 为例:
先执行 su gitlab-runner 切换到 gitlab-runner 账户 在你的主控端机器上使用 ssh-keygen 命令创建公钥,使用 ssh-keygen -t rsa 来创建,程序会询问存放目录,如果不需要修改,直接回车几次即可 将 ~/.ssh 目录下 id_rsa.pub 文件拷贝到受控机器的 ~/.ssh 目录中,然后将文件内容导入到 ~/.ssh/authorized_keys 文件 1 2 3 4 5 scp ~/.ssh/id_rsa.pub root@192.168.56.100:~/.ssh/id_rsa.pub cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys
在受控方机器设置权限: ~/.ssh 权限设置为 700,~/.ssh/authorized_keys 权限设置为 600
1 2 chmod 700 ~/.sshchmod 600 ~/.ssh/authorized_keys
之后在主控方机器就具备免密登录远程机器的能力 使用 sshpass 携带密码登录 参考:Linux 登录 ssh 携带密码(sshpass 方式)
安装 sshpass 1 apt-get/yum install sshpass -y
携带密码登录 1 sshpass -p '12345678' ssh -p 22 -tt <用户>@<IP>
执行命令 执行单一命令 1 2 3 4 5 6 7 8 9 10 [root@vps ~] /home/user anaconda-ks.cfg Centos7.img mwgt.tar.gz -------- anaconda-ks.cfg mwgt.tar.gz [root@vps ~]
执行本地脚本 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 [root@vps ~] pwd ls touch BBBBls ls /root[root@vps ~] Pseudo-terminal will not be allocated because stdin is not a terminal. /home/user anaconda-ks.cfg mwgt.tar.gz anaconda-ks.cfg BBBB mwgt.tar.gz ls : cannot open directory /root: Permission denied[root@vps ~] /home/user anaconda-ks.cfg mwgt.tar.gz anaconda-ks.cfg BBBB mwgt.tar.gz anaconda-ks.cfg [root@vps ~]
执行带参数的命令/脚本 1 2 3 4 5 6 7 8 9 10 11 [root@vps ~] echo $0 echo $1 echo $# [root@vps ~] bash vps1 1 [root@vps ~]
常见问题 Pseudo-terminal will not be allocated because stdin is not a terminal 当远程通过 ssh 登录主机时出现此错误,字面意思是伪终端将无法分配,因为标准输入不是终端。
解决方法是增加 -tt 参数来强制伪终端分配,即使标准输入不是终端。
1 ssh -tt user1@host1 -p 9527