linux命令expect实现ssh登陆


1 expect可用于自动化脚本的书写
yum -y install expect即可下载
 
2 脚本ssh.exp
#此行用于解释器,这样意味着你可以./ssh.exp了,或者不写这行直接/usr/bin/expect ssh.exp也行
#!/usr/bin/expect -f
 
#设置参数的方法是使用set,如果想获取命令行参数,则使用[ index $argv 0 ]表示获取第一个参数
set ip "localhost"
set passwd "liuliancao"
set timeout 10
 
#生成一个进程
spawn ssh liuliancao@$ip
expect "(yes/no)?" {send "yes\r";exp_continue}  #如果遇到了(yes/no)?这样的字符串就输入yes和换行符号,继续后面的expect,注意{前面有个空格,expect后面有个空格
expect "password:" {send "$passwd\r";interact} #如果遇到了password:这样的字符串就输入用户秘密,并保持交互
 
3 脚本ssh_without_passwd.exp
#!/usr/bin/expect -f
 
set ip [ lindex $argv 0 ]
set passwd [ lindex $argv 1 ]
 
 
spawn ssh-copy-id -i /root/.ssh/id_rsa  root@$ip
expect "yes/no" {send "yes\r";exp_continue}
expect "password:" {send "$passwd\r"}
 
interact

相关内容

    暂无相关文章