虚位以待(AD)
虚位以待(AD)
首页 > 脚本专栏 > linux shell > shell脚本无密码登录 expect的使用方法详解

shell脚本无密码登录 expect的使用方法详解
类别:linux shell   作者:码皇   来源:互联网   点击:

这篇文章主要介绍了shell脚本无密码登录 expect的使用方法详解的相关资料,希望通过本文能帮助到大家,需要的朋友可以参考下

shell脚本无密码登录 expect的使用方法详解

今天需要做一个定时任务脚本将最新的数据包文件传到远程的服务器上,虽然有密钥但也是要求输入密码的那种,所以只能另想办法实现让脚本自动输入密码了。

从网上查到使用expect可以,简单研究了一下,效果不错。 

因为我的操作系统没有安装expect,所以直接"yum -y install expect",你可以根据你的操作系统安装expect,或者源码编译。
安装好之后就可以使用了,这里有几种方法:

一、单独写一个脚本

如 auto_scp.sh:

    #!/usr/bin/expect #使用第一个参数 set server_ip [lindex $argv 0] #后面的也可以用参数[lindex $argv n] set server_port 22 set server_dir /home/testset server_user testset server_pswd testset scp_file auto_scp.sh # 设置超时时间 set timeout 60 spawn scp -P $server_port $scp_file $server_user@$server_ip:$server_dir expect {
    "passphrase" {
    send "$server_pswdn";
    }
    "password" {
    send "$server_pswdn";
    }
    "yes/no" {
    send "yesn";
    exp_continue;
    }
    }
    expect eof

我这里的变量都是随意设置的,你可以根据你的情况进行选择,保存退出之后,对该文件加上可执行权限,运行
"./auto_scp.sh 2.2.2.2"就可以了,"2.2.2.2"就是传入的第一参数。

"passphrase"和"password"等就是要监测的输入提示的一部分,send "$server_pswdn"就是要执行的命令。

二、在脚本中使用----我比较喜欢这个

我这里使用的是Here document方法。

    ...... ...... expect <<!! set timeout 60 spawn scp -P $server_port $scp_file $server_user@$server_ip:$server_dir expect {
    "passphrase" {
    send "$server_pswdn";
    }
    "password" {
    send "$server_pswdn";
    }
    "yes/no" {
    send "yesn";
    exp_continue;
    }
    }
    expect eof !! ......

变量都是我从配置文件中获取的,这里不再赘述了。

三、在脚本中使用

也是在脚本使用,但是不是用的Here document方法,而是使用expect -c 参数书,"-c"选项后面的字符串填充的就是命令。但是要注意本身字符串的转义符。

如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

您可能感兴趣的文章:

  • shell结合expect写的批量scp脚本工具
  • shell中嵌套执行expect命令实例
  • shell脚本通过expect实现自动单边无密登录功能
  • 利用expect命令实现Shell自动化交互的方法详解
相关热词搜索: shell脚本无密码登录 expect的使用 shell无