Linux使用expect自动登录,linux中使用expect实现自动登录(示例代码)
在實(shí)際生產(chǎn)使用中,比如執(zhí)行批量操作時(shí),我們不想創(chuàng)建ssh認(rèn)證,需要使用到密碼登錄或者鏈接,此時(shí)可以使用expect來(lái)操作自動(dòng)添加password:
在centos系統(tǒng)上expect默認(rèn)是沒(méi)有安裝的,所以首先應(yīng)先安裝expect:
yum install expect -y
創(chuàng)建expect腳本:[[email?protected]?script]#?cat?ssh_203.exp
#!/usr/bin/env?expect
set?timeout?5
set?remote_ip?"192.168.1.203"
set?passwd?"hh123456"
spawn?ssh?[email?protected]$remote_ip
expect?{
"(yes/no)?"?{send?"yes\n";exp_continue}
"password:"?{send?"$passwd\r"}
}
expect?"*#"
send?"cd?/data/script?&&?touch?mxd{1..10}\r"
interact
interact的作用是讓以上登錄后留在遠(yuǎn)程主機(jī)控制臺(tái)上,這樣不會(huì)退出遠(yuǎn)程主機(jī),僅用于ssh登錄。
執(zhí)行腳本:
[[email?protected] script]# ./ssh_203.exp ?(或者/usr/bin/expect ssh_203.exp)
以下為使用scp傳輸一個(gè)文件到遠(yuǎn)程主機(jī):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?[email?protected]$remote_ip:/data/script/
expect?{
"(yes/no)?"?{send?"yes\r";exp_continue}
"password:"?{send?"$passwd\r"?}
}
expect?eof
expect eof 表示執(zhí)行完成命令后退出遠(yuǎn)程主機(jī)
timeout則表示連接異常時(shí)等待的超時(shí)時(shí)間
以下為將文件傳輸帶遠(yuǎn)程主機(jī)并執(zhí)行: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?[email?protected]$remote_ip:/data/script/
expect?"password:"
send?$passwd\r
spawn?ssh?[email?protected]$remote_ip?"sh?/data/script/ssh_203.sh"
expect?"password:"
send?$passwd\r
expect?eof
總結(jié)
以上是生活随笔為你收集整理的Linux使用expect自动登录,linux中使用expect实现自动登录(示例代码)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 爱你留不住你是哪首歌啊?
- 下一篇: linux 脚本 符号,Shell脚