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

 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
expect批量执行命令

 

参数说明:
set:可以设置超时,也可以设置变量
timeout:expect超时等待时间,默认10S
spawn:执行一个命令
expect "":匹配输出的内容
exp_continue:继续执行下面匹配
\r:可以理解为回车
$argc:统计位置参数数量
[lindex $argv 0]:脚本后第一个参数,类似于shell中$1,以此类推
puts:打印字符串,类似于echo
awk -v I="$ip":赋值变量
expect{...}:输入多行记录
其他参数说明:
timeout -1:永不超时退出
log_file /var/log/expect.log:记录交互信息,一般crontab时使用
interact:交互后不退出远程终端,如果加要把expect "root@*" {send "exit\r"}注释掉,如果不加,就直接退出
将spawn ssh root@$ip换成spawn ssh -o StrictHostKeyChecking=no root@ip既不会再提示是否将服务器计算机密钥加入本地known_hosts

补充:

#ssh root@$ip > /dev/null 2>&1 << eeooff
#ls /tmp/
#exit
#eeooff
#echo done!

需要输入密码

 

posted @ 2020-09-11 10:39  酷酷的二连长  阅读(1941)  评论(0编辑  收藏  举报