• Linux


    简单模式:

    #!/usr/bin/expect -f   
    set timeout 5   
    spawn ssh root@192.168.0.1
    expect "*assword*"   
    send "root
    "   
    expect "#"   
    send "ifconfig 
    "   
    expect eof

    讲解:

    send:用于向进程发送字符串
    expect:从进程接收字符串 比如:expect "*assword*"
    spawn:启动新的进程 interact:允许用户交互

    怎么使用变量:
    #!/usr/bin/expect -f
    set port 22
    set user root
    set host 192.168.0.12
    set password root
    set timeout -1
    spawn ssh -D $port $user@$host "ifconfig"
    expect {  
    "*yes/no" { send "yes
    "; exp_continue}  
    "*assword:" { send "$password
    " }  
    }  
    expect "*#*"  
    send "ifconfig > /home/cfg 
    "
    send "exit
    "
    }

    讲解:

    expect {  
    "*yes/no" { send "yes
    "; exp_continue}  
    "*assword:" { send "$password
    " }  
    }  
    选择模式,exp_continue表示继续。

    通过读取配置文件获取变量:
    配置文件
    192.168.0.1 root
    192.168.0.2 root

       自动化登录脚本

    #!/usr/bin/expect -f
    set f [open ./ip r]  
    while { [gets $f line ]>=0 } {       
    set ip [lindex $line 0]     
    set pwd [lindex $line 1]
    spawn ssh $ip
    expect  "*password:" { send "$pwd
    " }
    expect "#"
    send "ifconfig 
    "
    send "exit
    "
    interact
    }

    讲解:

    可以多台服务器循环执行,是个非常使用的方式!

    自动化远程拷贝文件:

    #!/usr/bin/expect -f
    set port 22
    set user root
    set host 192.168.28.30
    set password root
    set timeout -1
    spawn scp $host:/home/cfg ./
    expect {
    "*yes/no" { send "yes
    "; exp_continue}
    "*assword:" { send "$password
    " }
    }
    expect eof

    讲解:

    原理和ssh一样

    远程执行命令后写入文件,再通过scp到本机服务器:

    #!/usr/bin/expect -f
    
    set port 22
    set user root
    set host 192.168.28.30
    set password root
    set timeout -1
    spawn ssh -D $port $user@$host "ifconfig"
    expect {
    "*yes/no" { send "yes
    "; exp_continue}
    "*assword:" { send "$password
    " }
    }
    expect "*#*"
    send "ifconfig > /home/cfg 
    "
    send "exit
    "
    interact
    spawn scp $host:/home/cfg ./
    expect {
    "*yes/no" { send "yes
    "; exp_continue}
    "*assword:" { send "$password
    " }
    }
    expect eof

    讲解:

    自动化运维,远程交互从服务器A上ssh到服务器B上,然后执行服务器B上的命令。

    http://www.cnblogs.com/Javame/p/4272440.html

  • 相关阅读:
    【好文收藏】家庭
    CSS选择器
    高等数学
    生也有涯而知也无涯,以有涯应无涯,殆矣
    navicat连接MySQL8+时出现2059错误解决方法
    Python 自己常用的方法
    Vue中变量名前加三个点代表什么意思
    Python3 locals函数的妙用
    python元类的应用
    vue + Element UI 之 rules校验
  • 原文地址:https://www.cnblogs.com/Javame/p/4281637.html
Copyright © 2020-2023  润新知