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 "[email protected]'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 [email protected]:/usr/local/liferay-portal/deploy/
set timeout 30000
expect "[email protected]'s password:"
set timeout 30000
send "$password\r"
set timeout 30000
send "exit\r"
expect eof

猜你喜欢

转载自blog.csdn.net/moliqin/article/details/72954240