Linux脚本知识

通过expect实现自动远程登陆的模板

  • 学会在shell脚本执行时读取密码而不是把密码直接赋值给一个变量
    read -p "Your Passwd: " -s PASSWARD #变量PASSWARD存放输入的密码

  • 在shell中插入使用expect
    expect< ...
    #expect codes...
    EOF

  • expect自动登陆不退出
    set timeout 10 #timeout is 10s
    spawn ssh $USER@$SERVER
    expect {
    "(yes/no)?"
    {
    send "yes\n"
    expect "assword:" { send "$PASSWARD"}
    }
    "
    assword:"
    {
    send "$PASSWARD"
    }
    }
    interact

  • expect自动登陆执行指定命令并退出
    spawn ssh $USER@$SERVER
    expect {
    "(yes/no)?"
    {
    send "yes\n"
    expect "assword:" { send "$PASSWARD"}
    }
    "
    assword:"
    {
    send "$PASSWARD"
    }
    }
    expect "# "
    send "$YOUR_CMD\n"
    expect "$EXPECT_PRINTS"
    send "exit\n"
    expect eof

你可能感兴趣的:(Linux脚本知识)