Linux服务器之间ssh免密登录设置&Linux远程ssh执行命令expect使用及几种方法
expect命令实现脚本免交互
一、Linux下SSH无密码认证远程执行命令
在客户端使用ssh-keygen生成密钥对,然后把公钥复制到服务端(authorized_keys)。
实现步骤:
1、客户端机器创建密钥对
# ssh-keygen -t rsa #一直回车
2、登录需要执行命令的ssh服务器,创建.ssh目录,设置好目录权限
mkdir /root/.ssh chmod 700 /root/.ssh
3、公钥上传到服务器,重命名为authorized.keys
scp /root/.ssh/id_rsa.pub root@服务端IP:/root/.ssh/authorized_keys # id_rsa.pub 可以追加多个客户端的公钥
4、设置ssh服务器
vi /etc/ssh/sshd_config RSAAuthentication yes #这三行取消注释,开启密钥对验证 PubkeyAuthentication yes AuthorizedKeysFile .ssh/authorized_keys PasswordAuthentication no #关闭密码验证
service sshd restart #centos 6 重启sshd服务
systemctl restart sshd #centos 7 重启sshd服务
5、免交互登陆测试,并查看远程主机home目录
ssh root@服务端IP "ls -l /home/"
二、expect工具实现免密交互
Expect是一个免费的编程工具语言,用来实现自动和交互式任务进行通信,而无需人的干预。 CentOS安装:yum install expect -y
CentOS离线安装方式:https://www.cnblogs.com/tozh/p/10096688.html
安装结束记得看一下expect的命令目录 :which expect
1、免交互查看远程主机内存
#!/bin/bash user=root pass='Admin@123' ip='172.20.2.89' /usr/local/bin/expect << EOF set timeout 30 spawn ssh $user@$ip expect { "(yes/no)" {send "yes\r"; exp_continue} "password:" {send "$pass\r"} } expect "root@*" {send "free -m\r"} expect "root@*" {send "exit\r"} expect eof EOF
2、批量执行命令
#!/bin/bash ip=`cat /root/ip.txt` user=root pass=Admin@123 for i in $ip; do expect -c " spawn ssh $user@$i expect { \"(yes/no)\" {send \"yes\r\"; exp_continue} \"password:\" {send \"$pass\r\"; exp_continue} \"root@*\" {send \"free -m\r exit\r\"; exp_continue} }" done
参数说明:set:可以设置超时,也可以设置变量timeout:expect超时等待时间,默认10Sspawn:执行一个命令expect "":匹配输出的内容exp_continue:继续执行下面匹配\r:可以理解为回车
1,以此类推puts:打印字符串,类似于echoawk−vI="
补充:
#ssh root@$ip > /dev/null 2>&1 << eeooff #ls /tmp/ #exit #eeooff #echo done!
需要输入密码
浙公网安备 33010602011771号