当前位置:首页 > 操作系统 > Linux

linux中使用expect实现自动登录

在实际生产使用中,比如执行批量操作时,我们不想创建ssh认证,需要使用到密码登录或者链接,此时可以使用expect来操作自动添加password:

在centos系统上expect默认是没有安装的,所以首先应先安装expect:

yum install expect -y

创建expect脚本:

[root@localhost script]# cat ssh_203.exp
#!/usr/bin/env expect
set timeout 5
set remote_ip "192.168.1.203"
set passwd "hh123456"
spawn ssh root@$remote_ip
expect {
        "(yes/no)?" {send "yesn";exp_continue}
        "password:" {send "$passwdr"}
}
expect "*#"
send "cd /data/script && touch mxd{1..10}r"
interact

interact的作用是让以上登录后留在远程主机控制台上,这样不会退出远程主机,仅用于ssh登录。

执行脚本:

[root@localhost script]# ./ssh_203.exp  (或者/usr/bin/expect ssh_203.exp)


以下为使用scp传输一个文件到远程主机:

cat 22.sh
#!/usr/bin/env expect
set timeout 5
set remote_ip "192.168.1.203"
set passwd "hh123456"
spawn scp -rp /data/script/ssh_203.sh root@$remote_ip:/data/script/
expect {
        "(yes/no)?" {send "yesr";exp_continue}
        "password:" {send "$passwdr" }
}
expect eof

expect eof 表示执行完成命令后退出远程主机

timeout则表示连接异常时等待的超时时间

以下为将文件传输带远程主机并执行:

cat 33.sh
#!/usr/bin/env expect
set timeout 5
set remote_ip "192.168.1.203"
set passwd "hh123456"
spawn scp -rp /data/script/ssh_203.sh root@$remote_ip:/data/script/
expect "password:"
send $passwdr
spawn ssh root@$remote_ip "sh /data/script/ssh_203.sh"
expect "password:"
send $passwdr
expect eof

原文:http://canonind.blog.51cto.com/8239025/1880113


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!

相关教程推荐

其他课程推荐