expect命令

本文介绍如何使用expect工具实现SSH远程登录自动化及密码输入,并利用rsync命令完成文件同步任务。文中提供了具体示例,包括expect脚本的编写、SSH连接自动化处理以及rsync同步文件的具体操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

expect是一个免费的编程工具语言,用来实现自动和交互式任务进行通信,而无需人的干预。

系统信息:

NAME="CentOS Linux"
VERSION="7 (Core)"
ID="centos"
ID_LIKE="rhel fedora"
VERSION_ID="7"
PRETTY_NAME="CentOS Linux 7 (Core)"
ANSI_COLOR="0;31"
CPE_NAME="cpe:/o:centos:centos:7"
HOME_URL="https://www.centos.org/"
BUG_REPORT_URL="https://bugs.centos.org/"

CENTOS_MANTISBT_PROJECT="CentOS-7"
CENTOS_MANTISBT_PROJECT_VERSION="7"
REDHAT_SUPPORT_PRODUCT="centos"
REDHAT_SUPPORT_PRODUCT_VERSION="7"

安装expect

yum -y install expect

测试shell脚本,通过ssh登录

#!/bin/bash

password="wei123"

expect <<EOF
set timeout 10
spawn ssh root@192.168.1.105
expect {
    "Are you sure you want to continue connecting (yes/no)?" {send "yes\r";exp_continue}
    "password:" {send "${password}\r"}
}
expect "]#"

send "exit\r"
expect eof
EOF
exit 0

 

使用rsync同步文件

安装rsync(客户端和服务器命令相同)

yum -y install rsync
systemctl start rsyncd
systemctl enable rsyncd

shell脚本

#!/bin/bash

doRsync()
{
    expect << EOF
    set timeout 3600
    spawn rsync -azPq $4 $1@$3:$5
    expect {
    "(yes/no)?" {send "yes\r";exp_continue}
    "password:" {send "${password}\r"}
    }
    expect eof
EOF
}

doRsync "root" "wei123" "192.168.1.105" "/home/export/" "/home/export"

 

脚本(传参,if):

#!/usr/bin/expect

set option [lindex $argv 0]

if {$option == "1"} {
    set url '/data/ops/database' 
} elseif {$option == "2"} {
    set url '/data/ops/analysis'
} else {
    set url '/home'
}

set timeout 3
spawn ssh root@192.168.1.100
expect "*password*"
send "aaaaa\r"
expect "*#"
send "cd $url\r"
interact

 

转载于:https://my.oschina.net/bobwei/blog/1861236

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值