shell脚本无密码登录 expect的使用方法详解
shell脚本无密码登录 expect的使用方法详解
Q:利用shell脚本实现ssh自动登录远程服务器?
今天需要做一个定时任务脚本将最新的数据包文件传到远程的服务器上,虽然有密钥但也是要求输入密码的那种,所以只能另想办法实现让脚本自动输入密码了。
A:expect命令
从网上查到使用expect可以,简单研究了一下,效果不错。
#!/usr/bin/expect
spawn ssh root@172.16.11.99
expect "*password:"
send "rootzhangr"
expect "*#"
interact
因为我的操作系统没有安装expect,所以直接"yum -y install
expect",你可以根据你的操作系统安装expect,或者源码编译。
安装好之后就可以使用了,这里有几种方法:
#!/usr/bin/expect //告诉操作系统,此脚本里的代码用expect这个shell来执行(类似与bash)
一、单独写一个脚本
shell> 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/test
set server_user test
set server_pswd test
set 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
1、使用expect -c的嵌套调用
我这里的变量都是随意设置的,你可以根据你的情况进行选择,保存退出之后,对该文件加上可执行权限,运行
"./auto_scp.sh 2.2.2.2"就可以了,"2.2.2.2"就是传入的第一参数。
如果需要在shell脚本中嵌套expect代码,就要使用expect -c "expect代码"
"passphrase"和"password"等就是要监测的输入提示的一部分,send "$server_pswdn"就是要执行的命令。
expect -c "
spawn ssh $user_name@$ip_addr df -P
expect {
"*(yes/no)?" {send "yesr" ; exp_continue}
"*password:" {send "$user_pwdr" ; exp_continue}
#退出
}
"
二、在脚本中使用----我比较喜欢这个
格式:spawn ssh登录远程主机 在该远程主机上要执行的命令(只能执行一条)
我这里使用的是Here document方法。
注意:在expect -c里面的代码,双引号要用转义字符。
......
......
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
!!
......
变量都是我从配置文件中获取的,这里不再赘述了。
2、使用here document的嵌套调用
三、在脚本中使用
#!/bin/bash
echo "123"
/usr/bin/expect <<EOF #利用here document的expect代码嵌套
spawn ssh root@172.16.11.99
expect "*password:"
send "rootzhangr"
expect "*#"
send "touch zhangjiacair"
expect "*#"
send "exitr"
expect eof #捕获结束
EOF
也是在脚本使用,但是不是用的Here document方法,而是使用expect -c 参数书,"-c"选项后面的字符串填充的就是命令。但是要注意本身字符串的转义符。
如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
expect详解-- programmed dialogue with interactive programs
您可能感兴趣的文章:
- shell结合expect写的批量scp脚本工具
- shell中嵌套执行expect命令实例
- shell脚本通过expect实现自动单边无密登录功能
- 利用expect命令实现Shell自动化交互的方法详解
是一个工具,是一个用来处理交互的命令。
借助Expect,我们可以将交互过程写在一个脚本上,使之自动化完成。
形象的说,ssh登录,ftp登录等都符合交互的定义。可以根据用户设定的规则和系统进程进行自动化交互,例如远程登陆的密码输入、自动化的执行远程命令。
威尼斯wns.9778官网活动,expect中最关键的四个命令是spawn、expect、send、interact
spawn:启动新的进程,后面可接shell命令
expect:从进程接收字符串
send:用于向进程发送字符串 interact:允许用户交互
1、spawn命令
spawn命令就是用来启动新的进程的。
本文由威尼斯wns.9778官网活动发布于计算机教程,转载请注明出处:shell脚本无密码登录 expect的使用方法详解
关键词: