Ubuntu expect使用经验

自动登录
 apt-get install  autossh
 apt-get remove expect
autossh.sh


set IPandPort yourport
set username  username
set remoteHost  xxx.xxx.xxx.xxx
set password yourpassword
 
while (1) {
    set connectedFlag 0;
    spawn /usr/bin/ssh -p $IPandPort $username@$remoteHost;
    match_max 100000;
    set timeout 60;
    expect {
        "?sh: Error*" 
            { puts "CONNECTION_ERROR"; exit; }
        "*yes/no*" 
            { send "yes\r"; exp_continue; }
        "*?assword:*" {
             send "$password\r"; set timeout 4;
             expect "*?assword:*" { puts "WRONG_PASSWORD"; exit; }
             set connectedFlag 1;
        }
        # if no password
        "*~*"
            { send "echo hello\r"; set connectedFlag 1; }
    }
    if { $connectedFlag == 0 } { 
        close;
        puts "SSH server unavailable, retrying..."; 
        continue; 
    }
 
    while (1) {
        set conAliveFlag 0;
        interact {
            # time interval for checking connection
            timeout 60 {
                set timeout 10;
                send "echo hello\r";
                expect "*hello*" { set conAliveFlag 1; }
                if { $conAliveFlag == 1 } { 
                    # connection is alive
                    continue;
                } else { break; }
            }
        }
    }
 
    close;
    puts "SSH connection failed, restarting...";
}
运行 ./autossh.sh

自动登录方法二 

#!/usr/bin/expect


set password yourpassword


spawn ssh  -p port  xxx.xxx.xxx.xxx


set timeout 30000


expect "root@xxx.xxx.xxx.xxx's password:"


set timeout 30000
send "$password\r"
send -- "\r"
interact    #这里非常重要,不然登录后不能操作
expect eof


自动拷贝文件至远端机器
#!/usr/bin/expect 
set password yourPasswor
spawn scp -P yourPort  /home/fileName.war root@xxx.xxx.xxx.xxx:/usr/local/liferay-portal/deploy/
set timeout 30000
expect "root@xxx.xxx.xxx.xxx's password:"
set timeout 30000
send "$password\r"
set timeout 30000
send "exit\r"
expect eof
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值