expect语言使用之自动切换账户或自动登录远程服务器

资料来源:

(1) https://baike.baidu.com/item/expect/4598715?fr=aladdin

(2) https://blog.csdn.net/gsjthxy/article/details/123441100?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522165568847216781685354744%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fblog.%2522%257D&request_id=165568847216781685354744&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~blog~first_rank_ecpm_v1~rank_v31_ecpm-1-123441100-null-null.nonecase&utm_term=%E8%87%AA%E5%8A%A8%E5%88%87%E6%8D%A2&spm=1018.2226.3001.4450

(3) https://www.cnblogs.com/liyuanhong/articles/10390785.html

(4) https://blog.csdn.net/three_man/article/details/45153441

1.linux中自动切换项目账户

1 #!/usr/bin/expect
2 
3 spawn su user_name        //其中,user_name为用户名,需要进行替换;
4 expect "Input Password:"  //其中,"Input Password:"为linux terminal上执行su操作而打印的信息,根据实际情况进行替换操作;
5 send "user_password\r"    //其中,user_password为用户密码,需要进行替换;
6 interact

2.linux中自动登录远程服务器

1 #!/usr/bin/expect
2 
3 set timeout 60
4 spawn ssh 远程服务器信息   //远程服务器信息需要进行替换;
5 expect "password:"          //password需要用ssh远程服务器时屏幕所打印的实际信息进行替换;
6 send  "user_password\r"   //user_password需要用用户密码进行替换:
7 interact

3.带命令行参数的expect脚本

#! /usr/bin/expect

set ip [lindex $argv 0];
set username [lindex $argv 1];
set password [lindex $argv 2];

set key_init "*yes/no*"
set key_password "[Pp]assword:"
set timeout 30
set prompt "(#|%|\\$) $"

spawn ssh ${username}@${ip}

expect {
    "$key_init" {
        send "yes\r" 
        expect "$key_password" {
            send "${password}\r" 
        }    
    }

    "$key_password" { send "${password}\r" }

    timeout { puts "Timed out during login"; exit 1 }
}

expect -re "$prompt"
send "exit\r"
expect eof { send_user "eof\r" }
————————————————
版权声明:本文为CSDN博主「three_man」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/three_man/article/details/45153441

 

 

 

posted on 2022-06-20 09:52  知北游。。  阅读(153)  评论(0编辑  收藏  举报

导航