zoukankan      html  css  js  c++  java
  • shell1(分发系统,expect)

    expect讲解
    expect可以让我们实现自动登录远程机器,并且可以实现自动远程执行命令。当然若是使用不带密码的密钥验证同样可以实现自动登录和自动远程执行命令。但当不能使用密钥验证的时候,我们就没有办法了。所以,这时候只要知道对方机器的账号和密码就可以通过expect脚本实现登录和远程命令。
    使用expect之前,需要先安装expect:
    yum install -y expect 

    1. 自动远程登录,并执行命令
    首先来看一个登录后不退出的脚本:

    vim 1.expect

    #! /usr/bin/expect
    set host "192.168.11.102"
    set passwd "123456"
    spawn ssh root@$host
    expect {
    "yes/no" { send "yes "; exp_continue}
    "assword:" { send "$passwd " }
    }
    interact

    chmod a+x 1.expect(加权限)

    ./1.expect(执行命令)

    退出用 logout

    2.登陆后,执行命令然后退出的脚本:

    vim 2.expect

    #!/usr/bin/expect
    set user "root"
    set passwd "123456"

    spawn ssh $user@192.168.11.18

    expect {
    "yes/no" { send "yes "; exp_continue}
    "password:" { send "$passwd " }
    }
    expect "]*"
    send "touch /tmp/12.txt "
    expect "]*"
    send "echo 1212 > /tmp/12.txt "
    expect "]*"
    send "exit "

    chmod a+x 2.expect

    ./2.expect(执行命令)

    3.传递参数

    vim 3.expect

    #!/usr/bin/expect
    set user [lindex $argv 0]
    set host [lindex $argv 1]
    set passwd "123456"
    set cm [lindex $argv 2]

    spawn ssh $user@$host

    expect {
    "yes/no" { send "yes "}
    "password:" { send "$passwd " }
    }
    expect "]*"
    send "$cm "
    expect "]*"
    send "exit "

    chmod a+x 3.expect

     ./2.expect root 192.168.11.18 “w”  (执行命令 ,使用其他命令要用双引号)

    4.自动同步文件

    vim 4.expect

    #!/usr/bin/expect
    set passwd "123456"
    spawn rsync -av root@192.168.11.18:/tmp/12.txt /tmp/
    expect {
    "yes/no" { send "yes "}
    "password:" { send "$passwd " }
    }
    expect eof

    chmod a+x 4.expect

    ./4.expect

    5.指定host和要同步的文件

    vim 5.expect

    #!/usr/bin/expect
    set passwd "123456"
    set host [lindex $argv 0]
    set file [lindex $argv 1]
    spawn rsync -av $file root@$host:$file
    expect {
    "yes/no" { send "yes "}
    "password:" { send "$passwd " }
    }
    expect eof

    chmod a+x 5.expect

    执行: ./4.expect 192.168.11.18 /tmp/12.txt  (远程机器的ip)

  • 相关阅读:
    Eureka的集群配置
    spring-cloud_Eureka服务注册与发现
    ADB常用命令
    教你如何修改Python的pip源镜像
    【vscode】【python】自定义代码自动补全
    【docker】删除docker中的运行日志
    MVC页面上多个提交按钮提交到不同的Action
    MongoDB在windows服务器安装部署及远程连接MongoDB
    sql如果存在就修改不存在就新增
    c#序列化和反系列化json与类型对象转换
  • 原文地址:https://www.cnblogs.com/pxmlinux/p/5556708.html
Copyright © 2011-2022 走看看