Linux expect 命令

本文介绍如何使用Expect脚本配合SSH命令实现文件的自动化上传过程。演示了如何读取本地文件路径并验证其存在性,获取用户确认后通过SSH连接远程服务器,并使用Expect处理交互式认证流程。

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

Linux expect命令

shell编程中用到telnet,ftp,ssh需要要人机交互的服务时,这时可以使用expect实现自动交互.

如果你怕写在shell脚本的中密码被别人看到,你可以通过shc对脚本进行加密:shc –r –f 脚本名

下面是一个ssh使用expect把文件存放到远程主机上的例子

#!/bin/bash

file_exist=false;

confirmed=false;

#程序绝对路径

while [ $file_exist = false ]

do

        echo -n "请输入程序路径,:/u/tiptop/azz/4gl/p_zx.4gl:";

        read filename;

        if [ -z $filename  ];

            then continue;

        else

            if [ -f $filename ];

                then file_exist=true;

            else

                echo "$filename 文件不存在";

            fi

     fi

done

while [ $confirmed = false ]

do

        echo -n "确认上传 y or n:"

        read c

        if [[ $c = y || $c = Y || $c = n || $c = N ]];

                then confirmed=true;

        else

                echo "请确认是否要上传"

        fi

done

if [[ $c = y || $c = Y ]];then

        target_filename=${filename}.`date +%Y_%m_%d_%H_%M_%S`

        #echo $filename

        expect <

        spawn ssh tiptop@10.134.x.x mv ${filename} ${target_filename}

        expect {

            #first connect, no public key in ~/.ssh/known_hosts

            "Are you sure you want to continue connecting (yes/no)?" {

            send "yes\r"

            expect "password:"

                send "mi_ma\r"

            }

            #already has public key in ~/.ssh/known_hosts

            "password:" {

                send "mi_ma\r"

            }

        }

        expect eof

        END1

        expect <

        spawn scp ${filename} tiptop@10.134.x.x:${filename}

        expect {

            #first connect, no public key in ~/.ssh/known_hosts

            "Are you sure you want to continue connecting (yes/no)?" {

            send "yes\r"

            expect "password:"

                send "mi_ma\r"

            }

            #already has public key in ~/.ssh/known_hosts

            "password:" {

                send "mi_ma\r"

            }

        }

        expect "*"

        send "exit\r"

        expect eof

        END2

        #记录log

        u_time=`date +%Y/%m/%d" "%H:%M:%S`

        ip=`who am i|cut -c37-80|sed s/")"//g`

        username=`whoami`

        echo "$username       $ip        ${u_time}        ${filename}" >> /u/out/upload.log

fi

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/7419833/viewspace-673700/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/7419833/viewspace-673700/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值