Linux远程ssh执行命令expect使用及几种方法

时间:2022-07-25
本文章向大家介绍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 "yesr"; exp_continue}
        "password:" {send "$passr"}
}
expect "root@*"  {send "free -mr"}
expect "root@*"  {send "exitr"}
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 "yesr"; exp_continue}
        "password:" {send "$passr"; exp_continue}
        "root@*" {send "free -mr exitr"; exp_continue}
    }"

done

参数说明:set:可以设置超时,也可以设置变量timeout:expect超时等待时间,默认10Sspawn:执行一个命令expect "":匹配输出的内容exp_continue:继续执行下面匹配r:可以理解为回车1,以此类推puts:打印字符串,类似于echoawk -v I="

补充:

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

需要输入密码